Skip to content

Instantly share code, notes, and snippets.

@ariefbayu
Last active January 2, 2018 03:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ariefbayu/30f631278ae22aa63a8890640fc91b0c to your computer and use it in GitHub Desktop.
Save ariefbayu/30f631278ae22aa63a8890640fc91b0c to your computer and use it in GitHub Desktop.
<?php
class JsonLoadAndCacher {
public $url;
public $hash;
//set cache directory here
private $fileLocation = 'd:/temp/';
public function LoadJson($url) {
$hash = md5($url);
//set your cached offline file as variable for ease of use
$cachedFile = $this->fileLocation . $hash;
//check if file exists
if (file_exists($cachedFile)) {
echo "cache exists\n";
//check if file age is within 24 hours
if(time() - filemtime($filename) > (24 * 3600)) {
echo "cache is within 24 hours\n";
return file_get_contents($cachedFile);
}
}
echo "cache doesn't exists or is older than 24 hours\n";
//cache doesn't exist of is older than 24 hours
//download it
$jsonFile = file_get_contents($url);
// Save content into cache
file_put_contents($cachedFile, $jsonFile);
//return downloaded content as result
return $jsonFile;
}
}
<?php
require_once('json-load-and-cacher.php');
$MyJson = new JsonLoadAndCacher;
$content = $MyJson->LoadJson('http://mysafeinfo.com/api/data?list=englishmonarchs&format=json');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment