Last active
January 2, 2018 03:33
-
-
Save ariefbayu/30f631278ae22aa63a8890640fc91b0c to your computer and use it in GitHub Desktop.
A simple script to help answer this SO question: https://stackoverflow.com/questions/48013106/fetch-and-cache-a-json-file/48021592#48021592
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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