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

大三角帆

我正在使用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'};

我搜索并找到了这个答案:在PHP中缓存JSON输出

我试图像这样合并它们:

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

我已经能够设置它,现在它获得了数据的第一个“回合”,但是第二个以及所有以下这些给了我一个错误:

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

我能做些什么?

PS:我已经将CHMOD 777目录

脑仓鼠

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

阅读手册以获取恐惧感,我想您可以通过更改以下内容来解决此问题

return fread($fh);

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章