我编写了一个使用 YQL 提取股票信息的函数,如下所示:
function quote_func() {
$BASE_URL = "https://query.yahooapis.com/v1/public/yql";
// Form YQL query and build URI to YQL Web service
$yql_query = "select * from yahoo.finance.quotes where symbol in ('AAPL')";
$yql_query_url = $BASE_URL . "?q=" . urlencode($yql_query) . "&format=json&env=http://datatables.org/alltables.env&callback=";
// Make call with cURL
$session = curl_init($yql_query_url);
curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
$json = curl_exec($session);
// Convert JSON to PHP object
$phpObj = json_decode($json);
// Confirm that results were returned before parsing
if(!is_null($phpObj->query->results)){
$quote = $phpObj->query->results->quote;
return $quote;
}
}
然后我显示我想要使用的信息:
<?php echo quote_func()->DATA-I-WANT; ?>
我知道这很糟糕,因为每次我使用该函数时,我都会执行 GET 请求。
至少有人能指出我正确的方向吗?
最佳答案
我建议您缓存结果。您可以将数据存储在数据库中,但最好的位置可能是适当的缓存,例如 memcached、APC,甚至只是文件系统。
这是一个非常简单的文件系统实现(未经测试,仅供说明)。
$cacheFile = '/tmp/myCache.txt';
$expirePeriod = 1800; // in seconds
if (file_exists($cacheFile) && time() - filemtime() < $expirePeriod) {
$quoteData = file_get_contents($cacheFile);
} else {
$quoteData = quote_func();
file_put_contents($cacheFile, $quoteData);
}
关于php - 使用 PHP 最小化 GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5706479/