下面是一个从REST XML API获取结果的简单代码示例。
这只是我从我的真实PHP类中提取的一小部分。
在返回XML文档的API URL中,我很好奇如何从一个页面获取所有结果,然后继续从下一个页面获取。
$this->api_page
设置接口从哪个页面返回数据。
看看下面使用SimpleXMLElement
的基本代码,我如何从10页或所有页返回数据,从一个页码开始,加载该页的结果,然后获取下一页,然后继续。
现在我正在用JavaScript和PHP来做这件事,用$_GET['page']
在URL中传递一个Page number
给我的脚本,这样做的问题是它需要用户加载页面,而且有点马虎。
我真正的API脚本将从服务器上的Cron作业运行,因此考虑到这一点,我如何获取所有页面?
我问这个问题是基于下面的示例代码,但也是因为这是我经常在其他项目中完成的任务,而我不知道做这件事的好方法?
<?php
$this->api_url = 'http://api.rescuegroups.org/rest/?key=' .$this->api_key.
'&type=animals&limit=' .$this->api_limit.
'&startPage='. $this->api_page;
$xmlObj = new SimpleXMLElement($this->api_url, NULL, TRUE);
foreach($xmlObj->pet as $pet){
echo $pet->animalID;
echo $pet->orgID;
echo $pet->status;
// more fields from the Pet object that is returned from the API call
// Save results to my own Database
}
?>
发布于 2013-01-31 20:35:25
基于你在一个非常稳定的环境中运行的假设,你可以像这样循环浏览页面:
<?php
$this->base_url = 'http://api.rescuegroups.org/rest/?key=' .$this->api_key.
'&type=animals&limit=' .$this->api_limit.
'&startPage=';
$start_page = $this->api_page;
$end_page = 10; //If you have a value for max pages.
// sometimes you might get the number of pages from the first returned XML and then you could update the $end_page inside the loop.
for ($counter = $start_page; $counter <= $end_page; $counter++) {
try {
$xmlObj = new SimpleXMLElement($this->base_url . $counter, NULL, TRUE);
foreach($xmlObj->pet as $pet){
echo $pet->animalID;
echo $pet->orgID;
echo $pet->status;
// more fields from the Pet object that is returned from the API call
// Save results to my own Database
}
} catch (Exception $e) {
// Something went wrong, possibly no more pages?
// Please Note! You wil also get an Exception if there is an error in the XML
// If so you should do some extra error handling
break;
}
}
?>
https://stackoverflow.com/questions/14633850
复制