This is some working code that I wrote to call a JSON file and cache it on my servers.
I'm calling the cached file. If the file exists I use json_decode on it. If the file doesn't exist I then call the JSON and decode that. Then after calling the JSON url, I write the contents to the cached file url.
$cache = @file_get_contents('cache/'.$filename.'.txt');
//check to see if file exists:
if (strlen($cache)<1) {
// file is empty
echo '<notcached />';
$JSON1= @file_get_contents($url);
$JSON_Data1 = json_decode($JSON1);
$myfile = fopen('cache/'.$filename.'.txt', "w");
$put = file_put_contents('cache/'.$filename.'.txt', ($JSON1));
} else {
//if file doesn't exist:
$JSON_Data1 = json_decode($cache);
echo '<cached />';
}
Instead of only using if (strlen($cache)<1) {
, is there a way that I can check the age of the $filename.txt and if it's older than 30 days grab the JSON url in the else statement?