Search code examples
phpjsoncaching

Caching JSON output in PHP


Got a slight bit of an issue. Been playing with the facebook and twitter API's and getting the JSON output of status search queries no problem, however I've read up further and realised that I could end up being "rate limited" as quoted from the documentation.

I was wondering is it easy to cache the JSON output each hour so that I can at least try and prevent this from happening? If so how is it done? As I tried a youtube video but that didn't really give much information only how to write the contents of a directory listing to a cache.php file, but it didn't really point out whether this can be done with JSON output and certainly didn't say how to use the time interval of 60 minutes or how to get the information then back out of the cache file.

Any help or code would be very much appreciated as there seems to be very little in tutorials on this sorta thing.


Solution

  • 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');
            $size = filesize($cacheFile);
            $cacheTime = trim(fgets($fh));
    
            // if data was cached recently, return cached data
            if ($cacheTime > strtotime('-60 minutes')) {
                return fread($fh, $size);
            }
    
            // 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.