I'm displaying Highcharts on my site which visualizes the data of an external API. Instead of calling this API with every pageview, I'd like to store the retrieved data locally in a cache file. The next user who visits the page then should get the Highcharts data from that local cache file, instead from the API URL (in order to reduce API calls and Highcharts load time). The cache file should be considered up-to-date for 60 minutes.
I've found an answer here 5-minute file cache in PHP, but it's not working for me.
I basically copied the code into my own php file:
....
//to be sure about the correct file path,
//I used here the absolute URL of my site: "https://www.example.com/path/to/my/cache.json"
$cache_file = "path/to/my/cache.json";
$api_url = "http://www.someapi.com/api";
if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 60 * 60 ))) {
// Cache file is less than 60 minutes old.
//Don't bother refreshing, just use the file as-is.
$json = file_get_contents($cache_file);
} else {
//Our cache is out-of-date, so load the data from our remote server,
//and also save it over our cache for next time.
$json = file_get_contents($api_url);
file_put_contents($cache_file, $json);
}
//decode JSON to array
$data = json_decode($json,true);
....
WhenI load my site, the the Highcharts are displaying the results but apparently only by the API URL. My cache.json file remains empty. I gave it chmod 777 and so I did for the parent directory data and dataCache.
In order to test the code, I tried to debug by out-commenting the line
//$json = file_get_contents($api_url);
What happens then is that the Highcharts don't display any data at all. So I learned that the IF loop is somewhat working - but not the way it should.
I then copied the JSON data from the API response, and saved it into my cache.json file. Now I out-commented the line
//$json = file_get_contents($api_url);
I was hoping that since I have a freshly created cache.json file, the first IF condition would be met and therefore the Highcharts would retrieve the data from my cache file. However, that didn't happen. The Highcharts don't display any data again.
Can you please help me understand why the code is not working (although I copied it basically from here 5-minute file cache in PHP)?
P.S.: I am not sure if this maybe just a "duplicate" question. But since the answer in the original question doesn't work for me, I was not sure how/where to ask.