Caching JSON output in PHP(在 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 输出
基础教程推荐
- PHP 守护进程/worker 环境 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01