Below is a simple example of code to fetch results from a REST XML API.
This is just a small portion I have extracted from my real PHP class for this question.
in the API URL which returns an XML document, I am curious about how I could fetch all the results from 1 page and then move on to fetch from the next page.
$this->api_page sets the page that the API returns data from.
Looking at the basic code below using SimpleXMLElement how could I for example return the data from 10 pages or all pages in the API starting at a page number, loading the results for that page and then fetching the next page an moving on.
Right now I am doing it with JavaScript and PHP by passing a Page number in the URL to my script using $_GET['page'] the problem with this is it requires a user to load the page and it’s kind of sloppy.
My real API script will be ran from a Cron job on the server, so with that in mind, how could I fetch all pages?
I ask this question based on this example code below but also because it is a task that I often have to do on other projects and I don’t know a good way of doing this?
<?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
}
?>
Based on the assumption that you run on a pretty stable environment you could loop through the pages like this: