2017-02-21 113 views
0

我试着为快速JSON响应制作缓存文件但我有一些问题我在PHP文件中得到了这段代码但我无法理解我该如何做到这一点对于任何JSON响应$url JSON文件我没有很多技巧请任何人都可以帮我这个问题如何在PHP的JSON请求中制作缓存文件

这里是代码什么我尝试

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

在此先感谢

回答

1

有多种您的代码出错。您可以使用file_put_contents简单地将内容添加到缓存文件。

试试下面的例子

$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); 
} 
+0

@hassan你好兄弟谢谢你的答案兄弟你的代码是好的,但请你可以改变财产以后在这个新的代码我的服务器不支持'file_get_contents'导致该选项使用过很多内存和请添加选项文件缓存启用禁用选项和什么关于ram使用file_put_content – Alish

+0

@hassan和兄什么类型的文件扩展名.json或其他,我可以添加选项从缓存文件夹删除所有缓存文件命令只有一个选项如'$ delete = true或false'我希望你明白我想说的话 – Alish

+0

@Alish你可以使用'unlink($ filena)开发工具来删除缓存文件我)' – Hassaan