Creating cache file from Instagram API Class

2019-08-29 05:13发布

I'm working with Cosenary Instagram PHP API Classes to fetch photos from instagram and try to create cache file to improve speed. Below is the snippet but it doesn't worked.

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);
}

I checked file instagram.json just leave blank file with 0 byte size. I'm using code to create cache file from other question here Caching Instagram API requests using PHP?

-- Edit --

If i replace $contents with json url, it works. But if i use $contents as part of API Class, it doesnt worked.

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));
}

1条回答
2楼-- · 2019-08-29 05:50

UPDATED ANSWER

<?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);
    }
}
查看更多
登录 后发表回答