13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

838 Chapter 33 Connecting to <strong>Web</strong> Services with XML <strong>and</strong> SOAP<br />

Using REST to Make a Request <strong>and</strong> Retrieve a Result<br />

With the set of class member variables already set at the beginning of the<br />

browseNodeSearch() function (or ASINSearch() or keywordSearch()), all that remains<br />

for using REST/XML over HTTP is to format <strong>and</strong> send the URL:<br />

$this->url = "http://ecs.amazonaws.com/onca/xml?".<br />

"Service=".$this->Service.<br />

"&Operation=".$this->Operation.<br />

"&AssociateTag=".$this->AssociateTag.<br />

"&AWSAccessKeyId=".$this->AWSAccessKeyId.<br />

"&BrowseNode=".$this->BrowseNode.<br />

"&ResponseGroup=".$this->ResponseGroup.<br />

"&SearchIndex=".$this->SearchIndex.<br />

"&Sort=".$this->Sort.<br />

"&TotalPages=".$this->TotalPages;<br />

The base URL in this case is http://ecs.amazonaws.com/onca/xml.To this, you append<br />

the variable names <strong>and</strong> their values to form a GET query string. Complete documentation<br />

on these <strong>and</strong> other possible variables can be found in the AWS Developer’s Guide.<br />

After you set all these parameters, you call<br />

$this->parseXML();<br />

to actually do the work.The parseXML() method is shown in Listing 33.10.<br />

Listing 33.10<br />

parseXML() Method—Parsing the XML Returned from a Query<br />

// Parse the XML into Product object(s)<br />

function parseXML() {<br />

// suppress errors because this will fail sometimes<br />

$xml = @simplexml_load_file($this->url);<br />

if(!$xml) {<br />

//try a second time in case just server busy<br />

$xml = @simplexml_load_file($this->url);<br />

if(!$xml) {<br />

return false;<br />

}<br />

}<br />

$this->totalResults = (integer)$xml->TotalResults;<br />

foreach($xml->Items->Item as $productXML) {<br />

$this->products[] = new Product($productXML);<br />

}<br />

The function simplexml_load_file() does most of the work for you. It reads in the<br />

XML content from a file or, in this case, an URL. It provides an object-oriented interface<br />

to the data <strong>and</strong> the structure in the XML document.This is a useful interface to the

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!