You are on page 1of 39

Create an Amazon storefront using PHP, Part 1: Getting content with Amazon ECS

How to build a storefront and display its wares


Skill Level: Intermediate Tyler Anderson (tyleranderson5@yahoo.com) Freelance Writer Stexar Corp.

25 Oct 2005 This is the first of a two-part tutorial titled "Create an Amazon storefront using PHP" that constructs an Amazon storefront using PHP and the Amazon E-Commerce Service (ECS). The storefront constructed will allow shoppers to view items displayed in lists or search for specific items in the store. Part 2 will cover the shopping cart, recommendation service, and constructing a collectibles shop.

Section 1. Before you start


This tutorial is for programmers interested in creating a storefront that automates the process of connecting to Amazon Web Services and displaying the result using PHP. This assumes you are familiar with basic PHP concepts, including for and while loops, and form handling. If you are uncertain of your PHP prowess, there are great tutorials available to help you get up to speed (see Resources). You should be familiar with Amazon Web Services, which are introduced in the developerWorks series "Boost application development with Amazon Web Services" (see Resources).

About this series

Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 1 of 39

developerWorks

ibm.com/developerWorks

In this two-part series, we create an Amazon shopping cart with PHP. Part 1 will cover the storefront architecture, displaying selections and browsing categories by communicating to Amazon Web Services through item search requests. We will also create a search box. Part 2 will cover creating, adding to, and modifying a shopping cart that will be stored entirely on Amazon servers using a technique called cart requests. We will cover building a collectibles shop and giving shoppers the ability to browse for similar items.

About this tutorial


We will build an Amazon storefront containing category links and a search box, allowing shoppers to browse categories in your store. Unlike most PHP applications, this one requires no local database, as data is stored on Amazon's servers. Therefore, this tutorial relies heavily on the Simple Object Access Protocol (SOAP), a Web services protocol that organizes information in XML. Web services is the way in which applications, like the PHP application you will build throughout this tutorial, communicate with central servers to obtain information. Through the Amazon E-Commerce Service (ECS), you will obtain and display content from categories that shoppers choose. When a category is selected, you will create parameters indicating that category, collect other relevant information, and launch a SOAP client. The SOAP client will take the parameters, form an XML document, and relay the XML document to the SOAP server. The Amazon server accesses its databases to create an XML document containing items that match the criteria. Finally, the server returns an XML document to your SOAP client, which parses it into a data structure from which you extract the requested data.

Prerequisites
To follow along with this tutorial, you will need to install and test the following tools, and retrieve two identifiers from Amazon: Web server Pick any Web server and operating system. Feel free to use Apache V2.X, or the IBM HTTP Server. PHP You can follow along in this tutorial without PHP, but if you are interested in interacting with the sample application, download PHP V5. Make sure to build PHP with --enable-soap to enable the PHP SOAP extensions. Amazon

Getting content with Amazon ECS Page 2 of 39

Copyright IBM Corporation 1994, 2008. All rights reserved.

ibm.com/developerWorks

developerWorks

You need two things from Amazon: a developer token and an Amazon Associates ID (see Resources). Web Browser You need a Web browser. These include Mozilla, Firefox, Opera, and Microsoft Internet Explorer.

Section 2. Overview
Amazon ECS
Amazon E-Commerce Service (ECS) allows anyone to connect to its vast inventory, display items on a Web site, tout the items, refer shoppers to Amazon for the sale, and get commission for it. Anyone can do it. All you need do is follow the application programming interface (API) from Amazon. "And you're done," as Amazon says. Your program will become a Web site, advertising and selling Amazon's products in one or more categories, earning you a commission for each referral. You do not need to stock items or process orders. Your only obligation is to maintain your code. In addition to using Amazon ECS with PHP in this tutorial, you will also design the storefront architecture and add functionality to it to allow searching within categories and for specific items.

Communicating with Amazon ECS


We will communicate with Amazon through SOAP using PHP and Web services. Web services, such as Amazon ECS, allow programmers to access a service. In this case, we will connect to Amazon ECS to obtain information about products. Listing 1 shows a sample SOAP message. Listing 1. Sample SOAP message

<soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/1999/XMLSchema"> <soap-env:Header/> <soap-env:Body> ... </soap-env:Body> </soap-env:Envelope>

Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 3 of 39

developerWorks

ibm.com/developerWorks

This is what a SOAP message looks like. In the PHP and Web services section, you will learn about how to use SOAP messages to make and receive requests from SOAP servers.

The storefront
Popular storefronts have clean, simple layouts. In this tutorial, we will design a basic storefront that's light on style so that we can focus on the mechanical parts that make it go. The finished product will have a side panel holding categories and a search box, displaying the items in the main content section on the right (see Figure 1). Figure 1. The final application

Getting content with Amazon ECS Page 4 of 39

Copyright IBM Corporation 1994, 2008. All rights reserved.

ibm.com/developerWorks

developerWorks

Categories
Most online stores have one or a small handful of categories. The storefront in this tutorial will contain a few categories, although when you build your own, you may choose as many categories as you'd like. The categories will be used as information in the SOAP request sent to Amazon ECS, which will return items that match the chosen category. Available categories are shown in Figure 2. Figure 2. Available categories

Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 5 of 39

developerWorks

ibm.com/developerWorks

The categories shown are possible SearchIndex values, which we will use to

Getting content with Amazon ECS Page 6 of 39

Copyright IBM Corporation 1994, 2008. All rights reserved.

ibm.com/developerWorks

developerWorks

search for items.

Items
By default, Amazon categories contain hundreds of pages full of items. Shoppers need to narrow their searches to find what they want. The item search you will design will search within categories for products and display the results to your shopper, showing similar results to the items displayed on Amazon. See figures 3 and 4. Figure 3. Items shown in the Baby category in the final application

Figure 4. Items shown in the Baby category on Amazon

Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 7 of 39

developerWorks

ibm.com/developerWorks

Notice that the first three items in Figure 4 are the same. Not all items appear in the exact same order. However, the items displayed are the same.

Section 3. What is Amazon ECS?


The Amazon E-Commerce Service (ECS) allows programmers to gain access to all the information found when browsing Amazon. This section will explore methods of retrieving information from Amazon.

Getting content with Amazon ECS Page 8 of 39

Copyright IBM Corporation 1994, 2008. All rights reserved.

ibm.com/developerWorks

developerWorks

Request types
There are several methods for searching for items or other content. Here, we will focus solely on ItemSearch. Part 2 will also use ItemSearch, as well as ItemLookup, CartCreate, CartAdd, CartModify, CartClear, and CartGet. Here's a list of all possible requests: BrowseNodeLookup -- Returns information about a specific Amazon product area CartAdd -- Adds an item to the cart. CartClear -- Removes all the contents of a cart. CartCreate -- Created with one item specified, this request creates a new cart. CartGet -- Retrieves the contents of a shopping cart. CartModify -- Used to modify quantity of items in a shopping cart. Setting a quantity to zero removes that item from the cart. Items may also be moved to and from the saved cart. CustomerContentLookup -- Used to retrieve publicly available content written by specific Amazon customers. CustomerContentSearch -- Allows you to search for Amazon customers by name or e-mail address. Help -- Used to retrieve information about developing with Amazon ECS. ItemLookup -- Allows you to retrieve information for up to 10 products by accessing reviews, similarities, etc. ItemSearch -- Used to search for products based on category and keywords. ListLookup -- Allows you to retrieve all items from a specific list. ListSearch -- Allows you to search for a wish list, baby registry, or wedding registry. SellerListingLookup -- Allows you to look up Amazon Shops and Marketplace products. SellerListingSearch -- Allows you to search for Amazon Shops and Marketplace listings. SellerLookup -- Allows you to retrieve information about specific

Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 9 of 39

developerWorks

ibm.com/developerWorks

sellers, including customer feedback ratings, location, etc. SimilarityLookup -- Allows you to retrieve similar items of a product. TransactionLookup -- Allows you to retrieve limited information on the status of transactions made by Amazon customers.

Understanding the parameters


Each request requires parameters for Amazon ECS to process your request properly. The parameters and their descriptions used in this series: Service -- This is always AWSECommerceService. SubscriptionId -- The developer token from Amazon. AssociateTag -- The Associates ID from Amazon. Operation -- The type of operation or request you will perform. Usually, you will just add Request to each request type. For the request type, ItemSearch, the operation will be ItemSearchRequest). For ItemLookup, the operation will be ItemLookupRequest, etc. ResponseGroup -- This is important because it tells Amazon how much information you want: from Small, Medium, and Large to specific parts of the available XML elements. Some available response groups: Accessories -- Returns a list of accessory items for each product in the list that has accessories. Cart -- Returns the shopping cart identifiers, as well as information specific to each product. Images -- Returns URLs for all images a product has. Offers -- Returns information about the offers for each product in the list. Small -- Provides a "Small" amount of information for each item in the list. Medium -- Provides a "Medium" amount of information for each item in the list. Large -- Provides a "Large" amount of information for each item in the list.

Getting content with Amazon ECS Page 10 of 39

Copyright IBM Corporation 1994, 2008. All rights reserved.

ibm.com/developerWorks

developerWorks

SOAP vs. REST


The data returned from the server for each request type is identical. However, both have differences in how the request is set up and used. REST requests are the simplest because they are long URLs containing the variables and their values for each item -- very similar to GET requests in PHP. SOAP requests, on the other hand, are more complex and are, thus, more powerful. They are XML documents transmitted to the SOAP server by way of HTTP. SOAP requests are more powerful than GET requests because they can accept more parameters, and several requests can be bundled in one SOAP XML document, which allows for simultaneous requests. Also, SOAP requests have priority, which improves the overall responsiveness of your store. You will use REST requests in this tutorial to learn the data returned from the server. In contrast, you will use SOAP requests in the final application (in Part 2) because they offer the potential to allow you to do much more than simple REST requests.

Simple REST request


You will be performing a REST request here to learn what the returned data is. Do an ItemSearch, as this is what you will be doing later in the tutorial. First, you will need to set up the parameters. The value of service will be AWSECommerceService, Operation will be ItemSearchRequest, ResponseGroup will be Small, SubscriptionId will be your developer token, and AssociateTag will be your Amazon Associates ID. Search through the Sporting Goods category, so SearchIndex will be SportingGoods, and search specifically for golf clubs, so Keywords will be golf clubs. Following is the URL, as shown in Listing 2. Listing 2. URL for the REST request
http://webservices.amazon.com/onca/xml?Service=AWSECommerceService &SubscriptionId=01AJBKQ38K8HM2R33Q82&Operation=ItemSearch &ResponseGroup=Small&AssociateTag=scubanecessit-20 &SearchIndex=SportingGoods&Keywords=golf%20clubs

Amazon ECS will now return an XML document containing information about the searched items.

REST response

Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 11 of 39

developerWorks

ibm.com/developerWorks

Because the response is so large, only a portion of it will be shown here. However, you can see the full response by pointing your browser to the URL in Listing 2. Listing 3 shows a snippet of the REST response. Here is where the items array begins. It plays back to the sender what the search terms were. The first <item> element begins the information for the first item in the response sent from Amazon ECS. It shows the ASIN, the item ID, a URL that -- if pointed to by the browser -- would display detailed information about the product. It also shows basic attributes, as we requested a small ResponseGroup, like the item's title.

Understanding Amazon's WSDL file


A Web Services Description Language (WSDL) file defines the information a Web service expects, as well as what it should return. This way, you can build your application without wondering what the information is that you need to send, where you're expected to send it, and what you can expect as a response. Amazon's WSDL file describes the available commands and syntax of possible lookup and search requests. Consider the ItemSearch entry in the above file, shown in Listing 4. For REST requests, the elements shown in Listing 5 are simply inserted into the ItemSearch element (Listing 3). The AWSECommerceService service defines where the request should be made, which is exactly what you used in the URL of your GET request in the REST response panel. Listing 5. ItemSearchRequest entry
<xs:complexType name="ItemSearchRequest"> <xs:sequence> <xs:element name="Keywords" type="xs:string" minOccurs="0" /> <xs:element name="ResponseGroup" type="xs:string" minOccurs="0" maxOccurs="unbounded" /> <xs:element name="SearchIndex" type="xs:string" minOccurs="0" /> ... </xs:sequence> </xs:complexType>

The WSDL file defines the structure of SOAP requests and responses, and REST responses. (REST requests are just URLs with encoded parameters.) Notice that the element named Request in Listing 5 defines the type of request that can be made, an ItemSearchRequest; and Listing 5 contains the structure of such a request, which makes the connection between the ItemSearch request and the ItemSearchRequest operation. You can refer to this file as you follow along, and again when you finish this tutorial and make plans to build your own application.

Getting content with Amazon ECS Page 12 of 39

Copyright IBM Corporation 1994, 2008. All rights reserved.

ibm.com/developerWorks

developerWorks

Section 4. PHP and Web services


In this section, you will learn how a simple SOAP request is sent and received via PHP, and how to extract data from the response in PHP.

Creating a SOAP request


To create the SOAP request, you need to set up the parameters. Because SOAP is more complex than REST, you will start with a simple example: the product in-stock checker. The XML document is shown in Listing 6. Listing 6. SOAP request in XML for the product in-stock checker
<soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/1999/XMLSchema"> <soap-env:Header/> <soap-env:Body> <tns:InStockQuantityRequest xmlns:tns="InStockByItemId" soap-env:encodingStyle= "http://schemas.xmlsoap.org/soap/encoding/"> <ItemId xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xsi:type="xsd:string">UWHD0023</ItemId> </tns:InStockQuantityRequest> </soap-env:Body> </soap-env:Envelope>

The code in Listing 6 is how the SOAP request would look in XML. It specifies an Envelope with an empty Header. The Body contains the parameters being sent. PHP can now send this request to the SOAP server via HTTP.

Creating a SOAP client in PHP


To create the SOAP client, you can take advantage of the built-in SOAP functionality of PHP:
<?php $client = new SoapClient("http://webservices.example.com/services/example.wsdl");

Next, you will transmit the request to the SOAP server.

Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 13 of 39

developerWorks

ibm.com/developerWorks

Transmitting the SOAP request in PHP


Now that the client has been created, you will need to set up the SOAP parameters and call the example function, InStockCheck, as shown in Listing 7. Listing 7. Set up the parameters and send the SOAP request
<?php $client = new SoapClient("http://webservices.example.com/services/example.wsdl"); $params = array( 'ItemId' => UWHD0023); $client->InStockCheck($params); ... ?>

The above code sends the SOAP request to the server specified in the WSDL file, the URL you used in your REST request. Now you will move onto the SOAP response.

The SOAP response


The SOAP response is also an XML document (see Listing 8). Listing 8. SOAP response in XML for the product in-stock checker
<soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/1999/XMLSchema"> <soap-env:Header/> <soap-env:Body> <tns:InStockQuantityResponse xmlns:tns=" InStockByItemId " soap-env:encodingStyle= "http://schemas.xmlsoap.org/soap/encoding/"> <InStockQuantity xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xsi:type="xsd:string">15</InStockQuantity> </tns:InStockQuantityResponse> </soap-env:Body> </soap-env:Envelope>

The resultant data structure holds the answer to your request in InStockQuantity. Next, you will receive and extract the needed data in PHP.

Receiving and extracting data from the response in PHP


The response is captured in PHP by the code in Listing 9.

Getting content with Amazon ECS Page 14 of 39

Copyright IBM Corporation 1994, 2008. All rights reserved.

ibm.com/developerWorks

developerWorks

Listing 9. Captured response


... $client-<InStockCheck($params); $result = $client-<InStockCheck($params); ... ?>

Simply set the variable, $result, to your SOAP call to InStockCheck. To extract the answer, InStockQuantity, use the code in Listing 10. Listing 10. Extract the answer
... $result = $client->lInStockCheck($params); $answer = $result->lInStockQuantity; ?>

You now know how to transmit and receive a simple SOAP request and response. Later, you will make more complex SOAP requests with hierarchy.

Handling faults
A fault can occur for a variety of reasons. To catch faults on your own, without exceptions, and display them to the screen, use the following PHP code. Listing 11. Handle a SOAP fault
... $result = $client->InStockCheck($params); $client = new SoapClient("http://webservices.example.com/services/example.wsdl"); $result = $client->InStockCheck($params); if(is_soap_fault($result)){ print("A fault occurred: " . $result->faultstring); } else{ $answer = $result->InStockQuantity; } ?>

If a problem occurs on your side or the server's, a fault will be returned in the SOAP response, and you will be notified with the above code. A fault looks just like a regular SOAP response. However, the variable faultstring contains the reason why a fault occurred.

Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 15 of 39

developerWorks

ibm.com/developerWorks

Section 5. Designing the storefront architecture


This section will cover the design of the storefront architecture. It will guide you through creating templates for your Web site that will be used to display a title, a side panel for categories, a search box for searching within categories, and footer at the end of each page.

Processing point: storeFront.php


Now that Web services have been covered, let's begin designing the storefront. Create a root directory for your storefront and create a file: storeFront.php. Begin coding it, as shown in Listing 12. Listing 12. Process requests and display storefront
<?php ... $title="Welcome to TylerCo."; require('header.php'); ... print(" <p>Welcome to TylerCo., where you will find great value and great service! Guaranteed!<p> Please browse the products on our Web site by clicking on one of the categories to the left"); ... require('footer.php'); ?>

The above will introduce your storefront. When a category is selected later, it will call a method that will connect to Amazon ECS and display returned category items or items corresponding to search terms.

Home link and title


The storeFront.php file is used to direct and receive all requests by your application, which you need to create the rest of the content to display as your storefront. Create a file named header.php and place it in the same directory as storeFront.php. Begin coding it as shown in Listing 13. Listing 13. Home link and title

Getting content with Amazon ECS Page 16 of 39

Copyright IBM Corporation 1994, 2008. All rights reserved.

ibm.com/developerWorks

developerWorks

<?php print(' <html> <title>'.$title.'</title> <body> <table width="750px" align="center" valign="top"> <tr><td colspan="2"> '); if(!isset($_GET['keyword']) && !isset($_GET['category'])){ print("Home"); } else{ print("<a href='storeFront.php"); print("'>Home</a>"); } ...

Here you print out the title, and, if needed, the home link. If the Web browser is pointed to storeFront.php, not to any keyword or category, then only the text Home will appear. However, if you're browsing categories, the link will appear, and clicking on it will clear the variables in the GET string and take you back to the main page.

The side panel: Categories


Next, you will need some categories to browse. Start out with five: Baby, Computers, Outdoor Living, Software, and Sporting Goods. Continuing with header.php, add the code as shown in Listing 14. Listing 14. Display category links
... print(' </td></tr> <tr><td colspan="2"> <center><h1>'.$title.'</h1>< /center></tr></td><tr><td height="100%"> <table width="135px" align="left" border="2px" height="100%"><tr><td valign="top"> <table width="135px"> <tr> <td><b>Categories</b></td> </tr> <tr> <td> <a href="storeFront.php?category=Baby&displayCat=Baby'. processGETString("cadikepa").'">Baby</a><br /> <a href="storeFront.php?category=PCHardware&displayCat=Computers'. processGETString("cadikepa").'">Computers</a><br /> <a href="storeFront.php?category=OutdoorLiving&displayCat=Outdoor Living'. processGETString("cadikepa").'">Outdoor Living</a><br /> <a href="storeFront.php?category=Software&displayCat=Software'. processGETString("cadikepa").'">Software</a><br /> <a href="storeFront.php?category=SportingGoods&displayCat=Sporting Goods'. processGETString("cadikepa").'">Sporting Goods</a>

Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 17 of 39

developerWorks

ibm.com/developerWorks

</td> </tr> <tr> <td>&nbsp;</td> </tr> </table> '); ...

Listing 14 starts by creating the side panel that will house the category links. When a customer clicks on one of the categories, the category and displayCat, the value to display for the current category, will be set in the URL. This way, your application can process the variables and display the appropriate items and information using the GET array. Figure 5 shows the current storefront with category links. Figure 5. Display the category links

The category links are shown in the left-side panel. Now you will move on to clicking from category to category. The processGETString will place the current variables in the GET array, propagating their values with each click in your storefront. This is important so that each time a customer clicks through your storefront, his current data is not lost. Place this function in functions.php, as shown in Listing 15.

Getting content with Amazon ECS Page 18 of 39

Copyright IBM Corporation 1994, 2008. All rights reserved.

ibm.com/developerWorks

developerWorks

Listing 15. Process and return the variables encoded in the URL
function processGETString($vetoString=''){ $string = ''; if($_GET['pagenum'] != '' && strstr($vetoString, 'pa') == '') $string .= "&pagenum=".$_GET['pagenum']; if($_GET['keyword'] != '' && strstr($vetoString, 'ke') == '') $string .= "&keyword=".$_GET['keyword']; if($_GET['category'] != '' && strstr($vetoString, 'ca') == '') $string .= "&category=".$_GET['category']; if($_GET['displayCat'] != '' && strstr($vetoString, 'di') == '') $string .= "&displayCat=".$_GET['displayCat']; return $string; }

This function concatenates all current variables to a single variable used for creating links, thus propagating the variable's values from one click to the next. The $vetoString variable that gets passed in as a parameter, with value cadikepa is used to signify that if that variable exists, its value will not be propagated. This is important when a customer wants to switch categories. Use displayCat to show the new category. The keyword and pagenum variables will need to be dropped altogether. Click on the Baby category, and notice the current category and displayCat values in the URL:
http://localhost.localdomain/amazon_ecs_part1/storeFront.php? category=Baby&displayCat=Baby

Now click on the Computers category.


http://localhost.localdomain/amazon_ecs_part1/storeFront.php? category=PCHardware&displayCat=Computers

See how the old category and displayCat values didn't get propagated? It's because they were vetoed by the processGETString() function by passing in 'ca' to veto category, and 'di' to veto displayCat.

The side panel: Search box


You have now set up the ability to browse categories. Next, you will add functionality to search in the current category by creating a search box, continuing with header.php, as shown in Listing 16. Listing 16. Display the search box

Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 19 of 39

developerWorks

ibm.com/developerWorks

... </table> '); if(isset($_GET['category'])){ print(' <table width="135px"> <tr> <td><b>Search within<br>this category</b></td> </tr> <tr> <td> <form name="search" action="storeFront.php" method="GET"> ... <input type="hidden" name="displayCat" value="'.$_GET['displayCat'].'" /> <input type="hidden" name="category" value="'.$_GET['category'].'" />'); print(' <input type="text" name="keyword" size="10" /> <input type="submit" value="Search" /> </form> </td> </tr> <tr> <td>&nbsp;</td> </tr> </table> '); ...

The HTML code in Listing 16 will display a search box. Once the Search button is pressed, it will submit the entered keyword, as well as the current displayCat and category variables as hidden inputs. This will allow your application to process the data and display the appropriate items as results. See the current storefront with the search box by clicking one of the category links, as shown in Figure 6. Figure 6. Display the search box

Getting content with Amazon ECS Page 20 of 39

Copyright IBM Corporation 1994, 2008. All rights reserved.

ibm.com/developerWorks

developerWorks

The search box is displayed in the left-side panel with a button. You will cover searching through items within categories in the Searching for items section. Now you will move on to the main content area.

Main content area: Setup and contents


For this part of the tutorial, the side panel is complete. There will be some other things to add to the panel in Part 2, so be sure to read that. Here, you will set up the main content area, where you will later display items returned from Amazon. The code will close off the side panel and begin the main content area:
print(' </td></tr></table> </td><td valign="top" width="100%">');

Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 21 of 39

developerWorks

ibm.com/developerWorks

The contents of the main content area are ready to be displayed. Before you do that, you need to finish it off with a footer.

Footer: Site information


Your footer will be a rather simple file, which you can make more complex if you want to at a later time. Create it, footer.php, and place it in the same directory as header.php. Place the following example code in it, as shown in Listing 17. Listing 17: Display the site and copyright info
</td></tr> <tr><td align="center" colspan="2"> <font size="2px"><br> <center>Copyright 2005, TylerCo.<br>Product/ information and pictures Copyright Amazon</center> </font> </td></tr></table> </body></html>

You can tailor your site and copyright information for your own application. This completes the storefront. Sample output shown by the browser after pointing to storeFront.php is shown in Figure 7. Figure 7. The completed storefront

Getting content with Amazon ECS Page 22 of 39

Copyright IBM Corporation 1994, 2008. All rights reserved.

ibm.com/developerWorks

developerWorks

Your storefront should include a title, a side panel with category links, an empty main content area to the right, and a footer displaying site and copyright information. The search box isn't shown here because a category hasn't yet been chosen. Now you will move onto the fun stuff and begin retrieving content from Amazon.

Section 6. Browsing categories


Now that your storefront is designed complete with category links, it's time to request data from Amazon ECS and display the returned items for customers to browse.

Retrieving the current category from the GET array


First you need to click on a category. Start by clicking on the Sporting Goods category, which you will process in storeFront.php, as shown in Listing 18.

Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 23 of 39

developerWorks

ibm.com/developerWorks

Listing 18. Process the category variable out of the GET array
... require('header.php'); if($_GET['category'] != ''){ printCategoryItems(); } else{ print(" <p>Welcome to TylerCo., where you will find great value and great service! Guaranteed!<p> Please browse the products on our Web site by clicking on one of the categories to the left"); }

This time, instead of introducing your storefront, the category variable in the GET array will exist, indicating to your application that a category has been selected, which will call printCategoryItems(). To see what the code in Listing 18 does, you can create an empty function, printCategoryItems() and place it in the functions.php file.

Validating a selected category


You have selected a category, and now you need to verify whether it is a valid category in your storefront. Create the following function in a file, functions.php, and place it in a subdirectory to your storefront called, includes, as shown in Listing 19. Listing 19. Verify that the selected category is valid in your storefront
define(TOKEN, "YourDeveloperTokenHere"); define(ASSOCID, "YourAssociatesIdHere"); function printCategoryItems(){ ... $category = $_GET['category']; $displayCat = $_GET['displayCat']; switch($category){ case 'Baby': case 'PCHardware': case 'OutdoorLiving': case 'Software': case 'SportingGoods': $innerTitle = "$displayCat"; break; default: print("The $category category doesn't exist"); return; } if(isset($_GET['pagenum'])){ $pagenum = $_GET['pagenum'];

Getting content with Amazon ECS Page 24 of 39

Copyright IBM Corporation 1994, 2008. All rights reserved.

ibm.com/developerWorks

developerWorks

} else{ $pagenum = "1"; } ...

Include this file at the top of storeFront.php. The first two lines define your developer token and Amazon Associates ID. You will need to replace these values with the ones you get from Amazon. If the category isn't valid, the method will return, notifying the customer. If it is valid, however, the title of the main content area will become the value used to display the category, which is more readable than using the code passed to Amazon as the category. The $pagenum variable indicates which page of the results Amazon will return for displaying to your customer.

Setting up the parameters


You can now set up the parameters that will be sent to Amazon ECS. For searching items within a category, you will use the parameters shown in Listing 20. Listing 20. Parameters for searching items within a category
... $pagenum = "1"; } $array = array('Operation' => 'ItemSearchRequest', 'ItemPage' => $pagenum, 'SearchIndex' => $category, 'ResponseGroup' => 'Medium', 'Keywords' => $displayCat); ...

The operation indicates to Amazon that you will perform an ItemSearchRequest, and the first page is 1, as indicated by ItemPage. SearchIndex specifies which category to search, and ResponseGroup tells Amazon how much info you want. You will use $displayCat as Keywords, indicating that you are going to ask for the entire category. The Keywords parameter is required and cannot be empty, so the $displayCat variable, containing the category display name, will be used as the keywords.

Creating a request function


Create another function in functions.php, which will send our request to Amazon and return the result, as shown in Listing 21. Listing 21. Send a request to Amazon ECS and return the result

Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 25 of 39

developerWorks

ibm.com/developerWorks

function callSOAPFunction($function, $array){ $params = array('Service' => 'AWSECommerceService', 'AssociateTag' => ASSOCID, 'SubscriptionId' => TOKEN, 'Request' => array($array)); $client = new SoapClient("http://webservices.amazon.com/AWSECommerceService /AWSECommerceService.wsdl", array('exceptions' => 0)); return $client->__soapCall($function, array($params)); }

This function takes a function name (as determined in the WSDL file), and the array of parameters you created in the previous panel. A new SOAP client is then created, pointing to the Amazon ECS WSDL file. The parameter 'exceptions' => 0 indicates that you will handle exceptions manually. Finally, you send the request to Amazon, indicating the function of the WSDL file you desire to use, $function, and the array of parameters, $params. If valid, the function will return a data structure containing items that match your search request.

Using the request function


You can now make the request by calling callSOAPFunction. Add the code to the printCategoryItems() function, as shown in Listing 22. Listing 22. Call callSOAPFunction and store the result in $result
... 'ResponseGroup' => 'Medium', 'Keywords' => $displayCat); $result = callSOAPFunction("ItemSearch", $array); ...

The result is now stored in $result, which can now be processed.

Displaying the items section


If your request was valid and everything worked, you can display the item information for your customer. Exception handling will be covered at the end of this section. Add onto the printCategoryItems() function, as shown in Listing 23. Listing 23. Determine if items were returned from the request, displaying the items, and page navigation

Getting content with Amazon ECS Page 26 of 39

Copyright IBM Corporation 1994, 2008. All rights reserved.

ibm.com/developerWorks

developerWorks

... $result = callSOAPFunction("ItemSearch", $array); $items = $result->Items->Item; if($items){ printItemsSection($innerTitle, $items); printPrevNextPage($result->Items->TotalPages, $pagenum); } } <><>>>>>>>>>

First, you need to retrieve the array of items from the returned SOAP construct, $items = $result->Items->Item. Next, if $items exist, printItemsSection() prints out all the items, and printPrevNextPage() will print out the page navigation links. Now you will need to loop through all the items in the $items array if it's an array, or print out the single item in $items if it isn't an array. See Listing 24 for the code and place this function in functions.php. Listing 24. Print the item's sections title and loop through all the items
function printItemsSection($title, $items){ print("<center><h3>$title</h3></center>"); print(" <table width='100%' border='0' cellspacing='5' cellpadding='0'>"); if(is_array($items)){ foreach($items as $i){ printItem($i); } } else{ printItem($items); } print("</table>"); }

The function printItem() gets called on every item element. This is where the actual HTML for each item will be sent to the Web browser. Add the function shown in Listing 25 to functions.php. Listing 25. Print an item by retrieving item data from the $i variable
function printItem($i){ print("<tr><td align='center' valign='top' rowspan='3'>"); print("<img border='0' src='".$i->SmallImage->URL."'>"); print("</td><td><font size='-1'> "); print("<b>".$i->ItemAttributes->Title."</b>< /font></td> </tr> "); $price = $i->OfferSummary->LowestNewPrice->FormattedPrice; print("<tr> <td align='left' valign='top'>"); print("<font size='-1'>Price: $price</font></td> </tr>"); print("<tr><td colspan=2>&nbsp;</td> </tr> "); }

Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 27 of 39

developerWorks

ibm.com/developerWorks

First, the image is displayed with the URL, $i->SmallImage->URL. Then, the name of the item, $i->ItemAttributes->Title, followed by the price, $i->OfferSummary->LowestNewPrice->FormattedPrice. Each item displayed is actually an object with various attributes that match the XML file returned in the SOAP response. Figure 8 shows the sample browser output of your application thus far. Figure 8. Display the first page of the Sporting Goods category

Next, you need navigation links to navigate between the pages of the category.

Displaying page navigation links


Getting content with Amazon ECS Page 28 of 39

Copyright IBM Corporation 1994, 2008. All rights reserved.

ibm.com/developerWorks

developerWorks

In Listing 23, there was a reference to the printPrevNextPage() function. Add this function, as shown in Listing 26, to functions.php. Listing 26. Retrieve the data for the previous and next page links, and display them
function printPrevNextPage($totalPages, $pagenum){ $previousPage = processPrevPage(); $nextPage = processNextPage($totalPages); print("<table width='100%'><tr><td width='33%' align='left'>"); print("$previousPage</td>"); print("<td width='33%' align='center'>Page ".$pagenum); print(" of $totalPages</td>"); print("<td width='33%' align='right'>$nextPage </td></tr></table>"); print("<font size='0'><br><center>The above information came from "); print("Amazon.com. We make no guarantees to the accuracy of the above "); print("information.</center></font>"); }

The function in Listing 26 calls two subfunctions: processPrevPage() and processNextPage(). The function takes the returned links and displays them, which allows customers to traverse pages. It also displays a disclaimer, noting that the author of the Web site isn't responsible for the information provided by Amazon. Add the code for functions, processPrevPage() and processNextPage(), to functions.php, as shown in listings 27 and 28. Listing 27. Calculate the previous page link
function processPrevPage($pagenum){ if($pagenum > 1){ $previousPage = "<a href='storeFront.php?pagenum=". ($pagenum-1). processGETString("pa"); $previousPage .= "'>Previous Page</a>"; } else{ $previousPage = "Previous Page"; } return $previousPage; }

Listing 28. Calculate the next page link


function processNextPage($totalPages, $pagenum){ if($pagenum < 300 && ($pagenum+1) <= $totalPages){ $nextPage = "<a href='storeFront.php?pagenum=".($pagenum+1). processGETString("pa"); $nextPage .= "'>Next Page</a>"; } else{

Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 29 of 39

developerWorks

ibm.com/developerWorks

$nextPage = "Next Page"; } return $nextPage; }

The code in these listings processes the link for the previous and next pages. Notice that the veto string for the processGETString() will be sent as pa, ensuring that the current pagenum variable isn't propagated. The code for displaying navigation links is now in place. See Figure 9 for sample browser output showing the navigation links. Figure 9. Display the navigation links at the bottom of the first page of the Sporting Goods category

Getting content with Amazon ECS Page 30 of 39

Copyright IBM Corporation 1994, 2008. All rights reserved.

ibm.com/developerWorks

developerWorks

Exception handling
Now that you have made the request, it is important to verify that no errors occurred. First, create a function, error(), as shown in Listing 29. Listing 29. Display error information
function error($msg, $err, $result){ print($msg); if(is_array($err)){ $msg2 = $err[0]->Message; } else{ $msg2 = $err->Message; } print($msg2); print_r($result->faultstring); print("<br><br>"); print_r($result); }

This function will display error information, providing that an error has occurred. Modify the printCategoryItems(), as shown in Listing 30. This code tests for errors and uses the new error() function. Listing 30. Test $result for errors and display error information, if true
... $result = callSOAPFunction("ItemSearch", $array); if($result->faultstring || $result->Items->Request->Errors){ error("Your search return 0 results, or perhaps there was an error processing your request. The returned XML file with additional error information is as follows:<br><br>", $result->Items->Request->Errors->Error, $result); } else{ $items = $result->Items->Item; if($items){ printItemsSection($innerTitle, $items); printPrevNextPage($result->Items->TotalPages, $pagenum); } } ...

There are two parts to look for in the returned SOAP construct. One is to check for $result->faultstring, and if a fault didn't occur, you need to check for errors in your request by reviewing $result->Items->Request->Errors. If either condition exists, error information will be displayed; otherwise, code execution will resume. Your application is coming together nicely! Now you will move onto the search box so your customers can better narrow down their searches.

Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 31 of 39

developerWorks

ibm.com/developerWorks

Section 7. Searching for items


In this section, you will learn how to use the search box you created in to set up the correct SOAP request and retrieve specific items within a category, allowing customers to concentrate their searches. This section will reuse a lot of the code from the Browsing categories section, so the goal of this section is to show you how to dynamically parameterize your item search requests to Amazon.

Retrieving submitted keywords from the search box


Before you retrieve submitted keywords, you will need to enter some keywords into the search box. Enter "golf clubs" into the keyword box, as shown in Figure 10. Figure 10. Enter keywords "golf clubs" in the keyword box

Getting content with Amazon ECS Page 32 of 39

Copyright IBM Corporation 1994, 2008. All rights reserved.

ibm.com/developerWorks

developerWorks

Now hit Enter or click the Search button. Now you will add to and parameterize the printCategoryItems() function using the keywords variable submitted via GET (see Listing 31). Listing 31. Retrieving the keyword variable from the GET array
function printCategoryItems(){ if(isset($_GET['keyword'])){ $keyword = $_GET['keyword']; $innerTitle = "Results for '$keyword' "; } $category = $_GET['category']; ...

This will allow you to parameterize the request sent to Amazon.

Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 33 of 39

developerWorks

ibm.com/developerWorks

Parameterize the search parameters


To parameterize the search parameters created in the $array construct, see Listing 32. Listing 32. Parameterize the parameters, $array, used to construct the request sent to Amazon
... print("The $category category doesn't exist"); return; } $array = array('Operation' => 'ItemSearchRequest', 'ItemPage' => $pagenum, 'SearchIndex' => $category, 'ResponseGroup' => 'Medium', 'Keywords' => getKeyword($keyword, $displayCat)); $result = callSOAPFunction("ItemSearch", $array); ...

Through getKeyword(), you can dynamically change the keywords passed to the item search request. Create a function, getKeyword(), and place it in the functions.php file (see Listing 33). Listing 33. Return the needed keyword, depending whether $keyword is set
function getKeyword(){ if($_GET['keyword'] == ''){ return $_GET['displayCat']; } else{ return $_GET['keyword']; } }

Thus, if keyword is set, meaning that a customer searched using the search box, the keyword will be returned from the function in Listing 33 and used as the Keywords input to the request, allowing you to change the input to the request dynamically. This is all you need to do to change the input parameters dynamically to the item search request. See the sample output for golf clubs in the Sporting Goods category in Figure 11. Figure 11. Search results for golf clubs in the Sporting Goods category

Getting content with Amazon ECS Page 34 of 39

Copyright IBM Corporation 1994, 2008. All rights reserved.

ibm.com/developerWorks

developerWorks

Notice that the results of your search terms match what you entered into the search box! You now have a functioning Web site, where users can browse items in specific categories of Amazon, as well as search for items within these categories.

Section 8. Summary
You have created an Amazon storefront in PHP that allows customers to browse categories and search for specific items within those categories. Your application successfully submits and receives requests to and from Amazon ECS, allowing you to display products on your Web site. In Part 2 of this series, you will create a shopping cart for your application, allowing customers to purchase items securely at
Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 35 of 39

developerWorks

ibm.com/developerWorks

Amazon -- and providing you with a commission.

Getting content with Amazon ECS Page 36 of 39

Copyright IBM Corporation 1994, 2008. All rights reserved.

ibm.com/developerWorks

developerWorks

Downloads
Description
Source code for the Amazon store, Part 1 Information about download methods

Name

Size

Download method
HTTP

os-amazonphpstore1.zip 4KB

Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 37 of 39

developerWorks

ibm.com/developerWorks

Resources
Learn For a series of tutorials designed to broaden your PHP skills, see "Learning PHP," Part 1, Part 2, and Part 3. "Boost application development with Amazon Web Services, Part 1" provides an overview of Amazon Web Services (AWS). AWS exposes raw product information and key parts of Amazon technology to third-party developers for use in their applications. "Boost application development with Amazon Web Services, Part 2: Introduction to the Amazon Simple Queue Service" is the second in a series on creating applications with Amazon Web Services and, in this installment, you can learn how to implement a Web service by using the Amazon Simple Queue Service. Learn how to configure Apache and PHP together. The default installation is PHP V4. Install PHP V5, and you shouldn't run into trouble. For more information about PHP SOAP, see the PHP manual: SOAP Functions. Back parameters for Amazon Web Services are available at General Parameters to all Operation Requests. The golden handbook on the Amazon E-Commerce Service (ECS) is Amazon Web Services WSDL File. Learn more about using WSDL with SOAP by reading "Using WSDL in SOAP applications." For more Web services information, including IBM's Web services tools, see New to SOA and Web services. For an excellent developerWorks article on PHP, Web services, and SOAP, read "Access an enterprise application from a PHP script." Visit the developerWorks Open source zone for extensive how-to information, tools, and project updates to help you develop with open source technologies and use them with IBM's products. Visit the developerWorks SOA and Web services zone for extensive information. Get products and technologies Before you begin to develop your Amazon storefront, you need an Amazon Web Services developer token. You also need an Amazon Associates ID. Innovate your next open source development project with IBM trial software,
Getting content with Amazon ECS Page 38 of 39

Copyright IBM Corporation 1994, 2008. All rights reserved.

ibm.com/developerWorks

developerWorks

available for download or on DVD. Discuss Get involved in the developerWorks community by participating in developerWorks blogs.

About the author


Tyler Anderson Tyler Anderson graduated with a degree in computer science from Brigham Young University in 2004 and is currently in his last semester as a master's student in computer engineering. In the past, he worked as a database programmer for DPMG.com, and he is currently an engineer for Stexar Corp., based in Beaverton, Ore.

Getting content with Amazon ECS Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 39 of 39

You might also like