在PHP中缓存JSON输出

时间:2012-07-10 06:04:42

标签: php json caching

稍微有点问题。一直在玩facebook和twitter API并且获取状态搜索查询的JSON输出没有问题,但是我已经进一步阅读并意识到我最终可能会被文档中引用的“速率限制”。

我想知道每小时缓存JSON输出是否容易,这样我至少可以尝试防止这种情况发生?如果是这样怎么办?当我尝试一个youtube视频,但实际上并没有提供太多信息如何将目录列表的内容写入cache.php文件,但它并没有真正指出这是否可以用JSON输出完成,当然没有说如何使用60分钟的时间间隔或如何获取信息然后退出缓存文件。

任何帮助或代码都会非常受欢迎,因为在这方面的教程中似乎很少有。

2 个答案:

答案 0 :(得分:29)

这是一个简单的函数,可以添加缓存以获取一些URL内容:

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;
}

它使用URL来标识缓存文件,下次将从缓存中读取对相同URL的重复请求。它将时间戳写入缓存文件的第一行,并丢弃超过一小时的缓存数据。这只是一个简单的例子,你可能想要自定义它。

答案 1 :(得分:5)

使用缓存来避免速率限制是个好主意。 以下是一些示例代码,展示了我如何为Google+数据执行此操作, 在我最近写的一些PHP代码中。

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

并使用它:

        // $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);
        }