Home > Amazon Wish Lists with SimpleXML

Amazon Wish Lists with SimpleXML

I recently upgraded my server to PHP5. One of the reasons was to do more development using Web services, that often return data in XML format. Parsing XML with the PHP4 XML Parser Functions can be a very tedious task, especially when the structure of the XML document is complex. Usually you need to write event handler functions for starting and closing elements and for the actual data.

With PHP5 XML processing finally became easy thanks to the SimpeXML functions, that convert an XML document to an object that can be processed using property selectors and array iterators.

A few days ago I integrated my Amazon wish list on this site with very few lines of code as you will see when you read the rest of this brief tutorial.

The Web Service Request

In the following code snippet the Amazon Web service request is issued and the XML data returned is saved in the variable $response. When the request fails an appropriate message is dispalyed and the execution of the script is stopped.

<?php
$request
= 'http://ecs.amazonaws.com/onca/xml?\
Service=AWSECommerceService&Operation=ListLookup&\
AWSAccessKeyId=YOUR-API-KEY&ListId=YOUR-LIST-ID\
&ListType=WishList&Sort=Price&ResponseGroup=\
EditorialReview,Images,ListItems,OfferSummary'
;

$response = file_get_contents($request);
if (!
$response) {
  die(
'Web service request failed');
}
?>

Note that the assignment of the request URL to $request is only one line without the backslashes. This is only to make the code fit in the layout of this site. When you want to use this code, you need to replace YOUR-API-KEY with your Amazon API key and YOUR-LIST-ID with your wish list id. When you request other types of lists you will also need to change the value of ListType.

The list of values of the ResponseGroup parameter determines what data is returned in the XML. In this example I ask for the editorial review, images, the items in the list, and the offer summery. The result items are sorted by price in ascending order.

Processing the Response

As mentioned above the whole XML document stored in $response is a PHP object. To access the properties of the individual list items a foreach loop is cycled through at the level of the list items. As you can see below each element in the document tree is an object.

<?php
foreach ($xml->Lists->List->ListItem as $items) {
 
$title = $items->Item->ItemAttributes->Title;
 
$price = $items->Item->OfferSummary->LowestNewPrice->FormattedPrice;
 
$asin = $items->Item->ASIN;
 
$img_src = items->Item->SmallImage->URL
  $desc
= strip_tags(
           
$items->Item->EditorialReviews->EditorialReview->Content
         
);
  if (
strlen($desc) > 300) {
   
$desc = substr($desc,0,299);
   
$desc = preg_replace("/\s+[,\.!?\w-]*?$/",'...',$desc);
  }
 
$href = 'http://www.amazon.com/gp/product/'.
 
$asin .'?ie=UTF8&tag=YOUR-ASSOCIATE-ID&linkCode=as2'.
 
'&camp=1789&creative=9325&creativeASIN='. $asin;
 
$buy = ' <a rel="nofollow" href="'. $href .'" title="'. $title .'">'.
 
'Buy for: '. $price .'</a>';
 
$html .= '<div style="clear:both;"><h3 class="title">'. $title .'</h3>';
 
$html .= '<div style="float:left;padding:5px 10px 5px 0;">'.
 
'<a rel="nofollow" href="'. $href .'"
  title="'
. $title .'"><img alt="" src="'. $img_src .'"/></a></div>';
 
$html .= '<div><p>'. $desc . $buy .'</p></div></div>';
}

print
$html;
?>

To make the code better readable I assign the values I want to display in the output to variables with "speaking" names.

Since product descriptions can be quite long and contain images I first strip all HTML markup and than set the maximum description length to 300 characters. To indicate that descriptions longer than 300 characters are shortened the end of the string is replaced with three dots. The regular expression in the preg_replace() function takes care that a cut off word at the end of the string is also thrown away.

One more thing worth mentioning is that the links to Amazon are associate (affiliate) links. If you are an Amazon associate replace YOUR-ASSOCIATE-ID with your id, else remove &tag=YOUR-ASSOCIATE-ID from the link.

The rest is simple HTML markup with some inline CSS. Inline CSS is actually not recommendable but since these rules are currently only used for one single page on my site, I decided not to add more classes to my CSS file.

Thanks to SimpleXML that's it! Enjoy playing around with Amazon or other Web services.

Very nice example. I have been using SimpleXML for all of my API stuff and I love it. It makes things so...simple. I have it tied into a base API class that other APIs can extend, like Flickr, Upcoming, Amazon, etc. This is a very simple example to achieve a specific task. Nice work.
Hey great article you wrote, very nice and informative, i like to learn more new things about php, that why i read your blog, now i can able to know about xml, that too simple xml, i have installed that, i will try this soon and let you know. Thanks for your informative article
Thanks for the tutorial, I will precise the form of request - there are no slashes, and better not to return the string: $request = 'http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&Operation=ListLookup&AWSAccessKeyId=YOUR_API_ID&ListId=YOUR_WISH_LIST&ListType=WishList&Sort=Price&ResponseGroup=EditorialReview,Images,ListItems,OfferSummary'; Between first and second block of the code, put this line: $xml = new SimpleXMLElement($response); For the details, read Amazon API: http://docs.amazonwebservices.com/AWSECommerceService/2008-06-26/DG/

You are right, I forgot to include the line with the call to SimpleXMLElement. The backslahes in the first code snippet are for better readability, which is indicated in the first sentence below the snippet.