沃梦达 / 编程问答 / php问题 / 正文

在 PHP 中缓存 JSON 输出

Caching JSON output in PHP(在 PHP 中缓存 JSON 输出)

本文介绍了在 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() . "
");
    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 输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 PHP 中缓存 JSON 输出

基础教程推荐