Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 19 ■ INTRODUCTION TO WEB SERVICES WITH SOAP^295

A Real-World Example


Now that you know the theory of web services, let’s look at an example of one of the most
su cc e s sf u l a nd w i del y u sed w eb ser v i ce A PIs o n t h e W e b, A m az o n W eb Ser vi c es. Us i ng th i s A PI,
you can get a ton of useful information.
For this example, you will try to find a list of books that have Pro PHP in the title or that are
published by Apress. To start, most web services require some sort of key that controls access
and that enforces some basic requirements, such as how many queries you use on a daily basis.
There’s no cost to get this key, but you will need to sign up for one at http://aws.amazon.com.
Once you’ve signed up, you will receive an e-mail confirming your subscription. At the end of
that e-mail will be a link to get your access key, which you should follow; you will need this key
shortly.
The URL for the WSDL for the Amazon Web Services API is currently http://
webservices.amazon.com/AWSECommerceService/AWSECommerceService.wsdl, and the file is
immense. You’re going to use only a very small subset of this WSDL, specifically the ItemSearch
operation. This method has some nested parameters. First, the Amazon Web Services request
requires the parameter AWSAccessKeyId to be passed along with another parameter named
Request. Request is an associative array of data and can contain many optional keys, which are
well documented on the Amazon Web Services site. For this example, you will search for this book
by Title and Publisher, using the SearchIndex 'Books' and asking for a small ResponseGroup back
from the server.
So without further introduction, Listing 19-8 demonstrates an Amazon SOAP request.

Listing 19-8. Finding Book Information Using the Amazon Web Services API

<?php
$wsdl = "http://webservices.amazon.com/AWSECommerceService/AWSECommerceService ➥
.wsdl";

$client = new SoapClient($wsdl);

$namedParameters = array(
'AWSAccessKeyId' => 'YOUR_ACCESS_KEY',
'Request' => array(
'Title' => 'Pro PHP',
'SearchIndex' => 'Books',
'ResponseGroup' => 'Small',
'Publisher' => 'Apress'
)
);

$response = $client->ItemSearch($namedParameters);
var_dump($response);

In this example, you set the WSDL file to the WSDL provided by the Amazon Web Services
and initialize a SoapClient. You create an array following the parameter format defined by the
WSDL and the API documentation, and pass along your access key plus an array of request

McArthur_819-9.book Page 295 Friday, February 29, 2008 8:03 AM

Free download pdf