2017-02-21 31 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