获取并缓存JSON文件

时间:2017-12-28 19:16:26

标签: php json caching

获取JSON文件并在服务器上缓存此文件的最佳方法是什么?我想从远程源获取一个JSON文件并对其进行缓存(例如24小时),因此它的网络容量会降低:)

class Json {
    public $url;
    public $hash;

    public function LoadJson($url) {
        // Exist function
        if (file_exists($hash)) {
            // Load md5 file
            return $hash;
        } else {
            $json_file = file_get_contents($url);
            $jfo = json_decode($json_file);
            // Save json file on server
            // Convert url to md5
        }
    }
}

$MyJson = new Json;
$MyJson->LoadJson('http://google.com/file.json');

1 个答案:

答案 0 :(得分:0)

您需要的关键因素是:

  • 您希望在哪里存储缓存的文件
  • 检查缓存是否存在且是否在24小时内
  • 如果不存在,请下载内容并将其保存到缓存文件中

这是我根据您的情况设法创建的课程:

class Json {
    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;
    }
}

以上课程中的片段测试:

Arief Bayu Purwanto@DESKTOP-H097T2S MINGW32 ~
$ php /d/temp/json-cache.php
cache doesn't exists or is older than 24 hours

Arief Bayu Purwanto@DESKTOP-H097T2S MINGW32 ~
$ php /d/temp/json-cache.php
cache exists
cache is within 24 hours

Arief Bayu Purwanto@DESKTOP-H097T2S MINGW32 ~