在PHP中缓存JSON请求 - 缓存文件错误

时间:2014-08-23 15:09:23

标签: php json caching

我正在使用weatherundeground.com获取天气数据,但我总是达到API调用限制,因此我考虑每60分钟缓存一次json响应。

这是我简单的php脚本

<?php
$json_string = file_get_contents("http://api.wunderground.com/api/apikey/conditions/forecast/lang:IT/q/CITY1.json");
$parsed_json = json_decode($json_string);

$city1 = $parsed_json->{'current_observation'}->{'display_location'}->{'city'};

我搜索并找到了这个答案:Caching JSON output in PHP

我试图像这样合并它们:

$url = "http://api.wunderground.com/api/apikey/conditions/forecast/lang:IT/q/SW/Acquarossa.json";
function getJson($url) {
// cache files are created like cache/abcdef123456...
$cacheFile = 'cache' . DIRECTORY_SEPARATOR . md5($url) . '.json';

if (file_exists($cacheFile)) {
    $fh = fopen($cacheFile, 'r');
    $cacheTime = trim(fgets($fh));

    // if data was cached recently, return cached data
    if ($cacheTime > strtotime('-60 minutes')) {
        return fread($fh);
    }

    // else delete cache file
    fclose($fh);
    unlink($cacheFile);
}

$json = file_get_contents($url);

$fh = fopen($cacheFile, 'w');
fwrite($fh, time() . "\n");
fwrite($fh, $json);
fclose($fh);

return $json;
}

$json_string = getJson($url);

$parsed_json = json_decode($json_string);

$city1 = $parsed_json->{'current_observation'}->{'display_location'}->{'city'};

我已经能够设置它,现在它获得了第一轮&#34;#34;数据,但第二个和所有以下,给我一个错误:

Warning: fread() expects exactly 2 parameters, 1 given in /home/*****/public_html/*****/acquarossa.php on line 27. 

如果我将缓存的json放在任何json验证器上,它会说它不是一个有效的json。

(这是缓存的文件:http://spinnaker.url.ph/meteo/cache/1f58bbab7bf88f3f8561b769475cb7c1.json

我该怎么办?

P.S。:我已经CHMOD 777目录

1 个答案:

答案 0 :(得分:2)

实际上,警告很明显是什么问题。 fread()需要2个参数,但您只能在第27行传递一个参数:return fread($fh);

阅读fread手册我猜您可以通过更改

来解决此问题
return fread($fh);

return fread($fh, filesize($chacheFile));