Alish
Alish

Reputation: 240

How To I make Cache File In PHP of Json Request

I'm Try To Make Cache File For Quick JSON Response But I have Some Problems I got This Code in a PHP File But I can't Understand How I can Make This For $url JSON File for any JSON Response I have No Many Skills Please anyone can help me for This Problem

Here is Code What i'm Try

function data_get_curl($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $uaa = $_SERVER['HTTP_USER_AGENT'];
    curl_setopt($ch, CURLOPT_USERAGENT, "User-Agent: $uaa");
    return curl_exec($ch);
}

$cache_option = true;
$id = 'DU6IdS2gVog';
$url = 'https://www.googleapis.com/youtube/v3/videos?key={Youtube_Api}&fields=items(snippet(title%2Cdescription%2Ctags))&part=snippet&id=DU6IdS2gVog';
$data = data_get_curl($url);
header('Content-Type: application/json');
echo $data;

function cache_set($id,$data,$time = 84600){
    if(!$cache_option) return NULL;
    $name = ROOT."/cache/".md5($id).".json";
    $fh = fopen($name, "w");
    fwrite($fh, serialize($data));
    fclose($fh);
}

function cache_get($id){
    if(!$cache_option) return NULL;
    $file = ROOT."/cache/".md5($id).".json";
    if(file_exists($file)){
        if(time() - 84600 < filemtime($file)){
            return unserialize(data_get_curl($file));
        }else{
            unlink($file);
        }
    }
    return NULL;
} 

Thanks In Advance

Upvotes: 0

Views: 1400

Answers (1)

Hassaan
Hassaan

Reputation: 7662

There are multiple errors with your code. You can simple use file_put_contents to add content to cache file.

Try the following example

$id = 'DU6IdS2gVog';
$cache_path = 'cache/';
$filename = $cache_path.md5($id);

if( file_exists($filename) && ( time() - 84600 < filemtime($filename) ) )
{
    $data = json_decode(file_get_contents($filename), true);
}
else
{
    $data = data_get_curl('https://www.googleapis.com/youtube/v3/videos?key={API_KEY}&fields=items(snippet(title%2Cdescription%2Ctags))&part=snippet&id='.$id);
    file_put_contents($filename, $data);
    $data = json_decode($data, true);
}

Upvotes: 2

Related Questions