問題描述
有點小問題.一直在玩 facebook 和 twitter API 并獲得狀態(tài)搜索查詢的 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 輸出是否容易,以便我至少可以嘗試防止這種情況發(fā)生?如果是這樣,它是如何完成的?因為我嘗試了一個 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.
推薦答案
這里有一個簡單的函數(shù),它添加緩存以獲取一些 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 的重復請求將在下次從緩存中讀取.它將時間戳寫入緩存文件的第一行,并丟棄超過一個小時的緩存數(shù)據(jù).這只是一個簡單的示例,您可能希望對其進行自定義.
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 輸出的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!