我使用weatherunderground.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'};
我搜索并发现这个答案:缓存JSON输出在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'};
我已经能够设置它,现在它得到第一个"轮"的数据,但第二个和以下所有,给我一个错误:
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)
我能做什么?
注::我已经CHMOD 777目录
实际上,警告非常清楚哪里出了问题。fread()
需要2个参数,但您只在第27行传递一个参数:return fread($fh);
return fread($fh);
return fread($fh, filesize($chacheFile));