API限制最多只能返回32张图片,但对于我们来说已经足够了。每张图片有三个尺寸,但是我们用普通的就可以。
PHP缓存API调用的结果,使得Instagram每小时请求服务器只有一次,这使得我们的程序请求和响应服务器的数量得到控制。
index.php
[html]
- <span >// 你可以从Instagram API取得页面的客户端ID
$instagramClientID = ''-- place your client id key here --'';
$api = ''https://api.instagram.com/v1/media/popular?client_id=''.$instagramClientID;
$cache = ''cache.txt'';
if(file_exists($cache) && filemtime($cache) > time() - 60*60){
// If a cache file exists, and it is
// fresher than 1 hour, use it
$images = unserialize(file_get_contents($cache));
}
else{
// 触发API请求和创建缓存文件
//取得图象
$response = file_get_contents($api);
$images = array();
// Decode the response and build an array
foreach(json_decode($response)->data as $item){
$title = '''';
if($item->caption){
$title = mb_substr($item->caption->text,0,70,"utf8");
}
$src = $item->images->standard_resolution->url;
$images[] = array(
"title" => htmlspecialchars($title),
"src" => htmlspecialchars($src)
);
}
// Remove the last item, so we still have
// 32 items when when the cover is added
array_pop($images);
// Push the cover in the beginning of the array
array_unshift($images,array("title"=>"Cover", "src"=>"assets/img/cover.jpg"));
// update the cache file
file_put_contents($cache,serialize($images));
}
# Generate the markup
$totalPages = count($images);
foreach($images as $i=>$image){
?>
<div id="page" >
<div >
<span >php echo $i+1?> // php echo $totalPages?>span>
<img src="" alt="" />
div>
div>
php
}span><span >
span>
文章TAG:网站建设 instagram 服务器