我可以使用 php 对 API 进行计划查询并将其保存在本地吗?


Can i make a scheduled query to an API using php and save it locally?

我做了一个从API检索信息的页面。从他们的服务器获得响应大约需要 10-20 秒。该请求是通过 PHP 代理通过 js 完成的,以避免跨域问题。我想知道,由于数据不像经常变化(它是国会议员的数据),我可能会每天发出请求并将其存储在我的服务器中,以便页面加载速度更快,我可以提供一个"刷新"按钮,以防用户需要它。怎么能做到这一点呢?我刚刚开始进行 Web 开发,我看到这是几种不同语言和框架的必要知识,现在我正在深入研究 js,但我让这个 PHP 黑客为我的请求工作,底线我对 PHP 几乎一无所知。

[编辑] 好的,我让 cron 工作了!现在如何从 php 脚本保存文档.xml?我试过了:

$c_t = fopen('file.xml', 'ab+');
fwrite($c_t, date('Y-m-d H:i:s')."'n'n"); //add timestamp to theverbose log
fwrite($c_t,$xml);

插入在"curl_close($session)"之前;

文件已保存,但仅带有时间戳...

这是我得到的...

<?php
// PHP Proxy --- only 'GET'
// Based on script from yahoo's example @ http://developer.yahoo.com/javascript/samples/proxy/php_proxy_simple.txt
// tweaked by vk
//  hostname - just base domain
define ('HOSTNAME', 'http://www.camara.gov.br');
// Get the REST call path from the AJAX application - js;
$path = $_GET['yws_path1'];
// assign yo url
$url = HOSTNAME.$path;
//Open the Curl session
$session = curl_init($url);
// Don't return HTTP headers. Do return the contents of the call
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_HTTPGET, true);
//set user agent, that did it!!! copied from browsers...
curl_setopt($session, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36');
// The web service returns XML. Set the Content-Type appropriately
header("Content-Type: text/xml");
// Make the call
$xml = curl_exec($session);
// done, shutDown.
curl_close($session);
?>

如果你使用的是Mac或Linux;你可以安排你的代码通过cron执行。 PHP 不必由浏览器运行。

php -f yourcode.php> results.txt

'man php' 了解更多信息...和'man crontab -s 5' 了解有关使用 cron 调度的详细信息