Aug 19 2008

I’ve started a decent amount of work on a new secret website I’m developing together with Tom. I’ll be using Amazon Web Services for a large part of the site, so I thought I’d post my experiences so far.

For the most of the part, its really simple, and using cURL (or a simpler file_get_contents) makes it work pretty well. All you gotta do is formulate a nice-looking URL, retrieve it, and parse the results using something easy like simplexml_load_string.

Lets take it in steps, lets set up the URL first:

// These stay the same for each query
$AmazonAssociateID = "xxx123";
$AWSAccessKey = "your_access_key";
$AWSAPIVersion = "2008-06-28";
 
// This is the query building part
$Operation = "ItemSearch";
$SearchIndex = "Blended"; // Like searching the WHOLE of amazon.co.uk
$ResponseGroup = "ItemAttributes,Images";
$Keywords = "Harry Potter";
 
// Glue together the whole URL
$url = "http://ecs.amazonaws.com/onca/xml"
		. "?Service=AWSECommerceService"
		. "&AssociateTag=" . $AmazonAssociateID
		. "&AWSAccessKeyId=" . $AWSAccessKey
		. "&Operation=" . $Operation
		. "&Version=" . $AWSAPIVersion
		. "&ResponseGroup=" . $ResponseGroup
		. "&Keywords=" . $Keywords;

When you sign up for AWS and Amazon Associates, you will be given your AWS access key and associate ID. Put those in the $AmazonAssociateID and $AWSAccessKey boxes. API versions are regularly released, so this version of my code is compliant with the AWS release made on 28th June 2008 (co-incidentally, my birthday!).

// Retrieve the URL
$response = file_get_contents($url);
// Or use cURL...
 
// Or if you can't get that to work, here is a dirty wget hack...
ob_start();
$ua = "Asgrim's AWS Client v1.0";
passthru("wget -U '{$ua}' -q -O - '{$url}'");
$response = ob_get_contents();
ob_end_clean();

There are three ways of retrieving the XML. First and easiest is a simple file_get_contents as on Line 26. Some hosts have the PHP setting allow_url_fopen = Off, meaning this will not work. Your alternative is to use curl (sometimes dodgy), or my wget hack listed from Line 30.

$xdoc = simplexml_load_string($response);
 
// Validate response
$success = true;
if($xdoc->Items->Request->Errors)
{
	foreach($xdoc->Items->Request->Errors->Error as $error)
	{
		$success = false;
		echo "{$error->Code}: {$error->Message}";
	}
}

The parsing is simple and uses simplexml. I won’t actually demonstrate using the result as it’s pretty self explanatory. The validation is simple as well anyway, and is self-explanatory.

And that’s all there is to it… easy as pie. If you want the whole file, you can download it here.

One Response to “Beginning AWS”

  1. Chris Dean says:

    Look through the AWS PHP code examples on the amazon developers site, there a couple of good ones – crap code but illustrates the process

    Also have a look at this for the download:
    Universal File Download Class:
    http://refactormycode.com/codes/440-universal-file-download-class

Leave a Reply