I am using weatherundeground.com to get weather data but I always reach the API calls limit so I was thinking about caching the json response every 60 minutes.
This is my simple php script
<?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'};
I searched and found this answer: Caching JSON output in PHP
I tried to merge them like this:
$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'};
I have been able to set it up and now it gets the first "round" of data, but the 2nd one and all the following, give me an error:
Warning: fread() expects exactly 2 parameters, 1 given in /home/*****/public_html/*****/acquarossa.php on line 27.
And if I put the cached json on any json validator, it says that it isn't a valid json.
( this is the cached file: http://spinnaker.url.ph/meteo/cache/1f58bbab7bf88f3f8561b769475cb7c1.json )
What can I do?
P.S.:I already CHMOD 777 the directory