在PHP中缓存JSON输出 [英] Caching JSON output in PHP

查看:246
本文介绍了在PHP中缓存JSON输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一点问题.一直在使用facebook和twitter API并获得状态搜索查询的JSON输出,但是,我进一步阅读并意识到,我最终可能会受到文档中引用的费率限制".

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.

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

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.

推荐答案

以下是一个简单的函数,它为获取一些URL内容添加了缓存:

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

它使用URL标识缓存文件,下一次将从缓存中读取对相同URL的重复请求.它将时间戳记写入高速缓存文件的第一行,并且丢弃早于一个小时的高速缓存数据.这只是一个简单的示例,您可能需要对其进行自定义.

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.

这篇关于在PHP中缓存JSON输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆