我正在使用Cosenary Instagram PHP API Classes从Instagram获取照片并尝试创建缓存文件以提高速度。以下是片段,但它不起作用。
include('conf.php');
require 'bigflannel-instafeed/data/instagram.class.php';
// Initialize class
$instagram = new Instagram($accessToken);
$instagram->setAccessToken($accessToken);
$contents = $instagram->getUserMedia($userID,$settings['count']);
$cache = './instagram.json';
if(file_exists($cache) && filemtime($cache) > time() - 60*60 && filesize($cache) < 10){
// If a cache file exists, and it is newer than 1 hour and file size bigger than 10 bytes, use it
$instaData = file_get_contents($cache);
} else {
$instaData = file_get_contents($contents);
file_put_contents($cache,$instaData);
}
我检查文件instagram.json只留下0字节大小的空白文件。 我正在使用代码从其他问题创建缓存文件Caching Instagram API requests using PHP?
- 编辑 -
如果我用json url替换$ contents,它就可以了。但是,如果我使用$ contents作为API类的一部分,它就不起作用。
include('conf.php');
require 'bigflannel-instafeed/data/instagram.class.php';
// Initialize class
$instagram = new Instagram($accessToken);
$instagram->setAccessToken($accessToken);
$contents = json_encode($instagram->getUserMedia($userID,$settings['count']));
$cache = './instagram.json';
if(file_exists($cache) && filemtime($cache) > time() - 60*60 && filesize($cache) > 10){
// If a cache file exists, and it is newer than 1 hour, use it
$jsonData = json_decode(file_get_contents($cache));
} else {
$jsonData = json_decode((file_get_contents("https://api.instagram.com/v1/users/3/media/recent/?access_token=180213154.f59def8.f888fe332f7c47e98bd20a44866ef0be&count=34")));
file_put_contents($cache,json_encode($jsonData));
}
答案 0 :(得分:2)
更新的答案
<?php
require 'instagram.class.php';
$cache = './cache.json';
if(file_exists($cache) && filemtime($cache) > time() - 60*60){
// If a cache file exists, and it is newer than 1 hour, use it
$response = json_decode(file_get_contents($cache),true); //Decode as an json array
} else {
$instagram = new Instagram($accessToken);
$instagram->setAccessToken($accessToken);
$response = $instagram->getUserMedia($userID, $settings['count']);
if($response){
file_put_contents($cache,json_encode($response)); //Save as json
}
}
echo "<pre>";
if(is_array($response)){
foreach($response['data'] as $data){
print_r($data);
}
}