duandie0884 2017-02-21 11:16
浏览 73
已采纳

如何在PHP的Json请求中创建缓存文件

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

  • 写回答

1条回答 默认 最新

  • dongzhengzhong1282 2017-02-21 12:43
    关注

    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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件