2017-12-28 30 views
1

JSONファイルをフェッチしてサーバーにキャッシュする最良の方法は何ですか?私は、リモートソースからのJSONファイルを取得し、(24時間など)、それをキャッシュしたいので、以下のインターネット容量をコスト:)JSONファイルのフェッチとキャッシュ

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'); 

答えて

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 [email protected] MINGW32 ~ 
$ php /d/temp/json-cache.php 
cache doesn't exists or is older than 24 hours 

Arief Bayu [email protected] MINGW32 ~ 
$ php /d/temp/json-cache.php 
cache exists 
cache is within 24 hours 

Arief Bayu [email protected] MINGW32 ~ 
関連する問題