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

时间:2013-10-08 00:32:31

标签: javascript php

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

[edit] 确定我让cron工作了!现在我如何从php脚本保存document.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);
?>

1 个答案:

答案 0 :(得分:4)

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

php -f yourcode.php&gt; RESULTS.TXT

'man php'获取更多信息...... 和 'man crontab -s 5'有关使用cron进行日程安排的详细信息

相关问题