私はこの投稿が古いことを知っていますが、それはGoogleに表示されるので、探しているすべての人のために、JSON URLをカールして特定のフォルダーにあるファイルにキャッシュするこの単純なものを作成しました。 5分経っていない場合はカールしてください。ファイルから表示されます。タイムスタンプを使用して時間を追跡します。
function ccurl($url,$id){
$path = "./private/cache/$id/";
$files = scandir($path);
$files = array_values(array_diff(scandir($path), array('.', '..')));
if(count($files) > 1){
foreach($files as $file){
unlink($path.$file);
$files = scandir($path);
$files = array_values(array_diff(scandir($path), array('.', '..')));
}
}
if(empty($files)){
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_TIMEOUT, 15);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_USERAGENT,
'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0');
$response = curl_exec($c);
curl_close ($c);
$fp = file_put_contents($path.time().'.json', $response);
return $response;
}else {
if(time() - str_replace('.json', '', $files[0]) > 300){
unlink($path.$files[0]);
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_TIMEOUT, 15);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_USERAGENT,
'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0');
$response = curl_exec($c);
curl_close ($c);
$fp = file_put_contents($path.time().'.json', $response);
return $response;
}else {
return file_get_contents($path. $files[0]);
}
}
}
使用法として、キャッシュされたすべてのファイル用のディレクトリを作成します。私にとっては/private/cache
、たとえば x のようなリクエスト キャッシュ用に別のディレクトリを作成します。関数を呼び出すときは、htis のようにする必要があります
ccurl('json_url','x')
。x は ID です。質問がある場合は、pls に尋ねてください。 ^_^ またお楽しみください (後で更新するかもしれないので、ID にディレクトリを使用しません)