Caching JSON output in PHP Caching JSON output in PHP json json

Caching JSON output in PHP


Here a simple function that adds caching to getting some URL contents:

function getJson($url) {    // cache files are created like cache/abcdef123456...    $cacheFile = 'cache' . DIRECTORY_SEPARATOR . md5($url);    if (file_exists($cacheFile)) {        $fh = fopen($cacheFile, 'r');        $cacheTime = trim(fgets($fh));        // if data was cached recently, return cached data        if ($cacheTime > strtotime('-60 minutes')) {            return fread($fh);        }        // else delete cache file        fclose($fh);        unlink($cacheFile);    }    $json = /* get from Twitter as usual */;    $fh = fopen($cacheFile, 'w');    fwrite($fh, time() . "\n");    fwrite($fh, $json);    fclose($fh);    return $json;}

It uses the URL to identify cache files, a repeated request to the identical URL will be read from the cache the next time. It writes the timestamp into the first line of the cache file, and cached data older than an hour is discarded. It's just a simple example and you'll probably want to customize it.


It's a good idea to use caching to avoid the rate limit. Here's some example code that shows how I did it for Google+ data,in some php code I wrote recently.

private function getCache($key) {    $cache_life = intval($this->instance['cache_life']); // minutes    if ($cache_life <= 0) return null;    // fully-qualified filename    $fqfname = $this->getCacheFileName($key);    if (file_exists($fqfname)) {        if (filemtime($fqfname) > (time() - 60 * $cache_life)) {            // The cache file is fresh.            $fresh = file_get_contents($fqfname);            $results = json_decode($fresh,true);            return $results;        }        else {            unlink($fqfname);        }    }    return null;}private function putCache($key, $results) {    $json = json_encode($results);    $fqfname = $this->getCacheFileName($key);    file_put_contents($fqfname, $json, LOCK_EX);}

and to use it:

        // $cacheKey is a value that is unique to the        // concatenation of all params. A string concatenation        // might work.         $results = $this->getCache($cacheKey);        if (!$results) {            // cache miss; must call out            $results = $this->getDataFromService(....);            $this->putCache($cacheKey, $results);        }