A php web service client

xiaoxiao2021-03-06  100

BY

Adam Trachtenberg, Coauthor of

PHP cookbook

07/03/2003

Web services allow you to exchange information over HTTP using XML. When you want to find out the weather forecast for New York City, the current stock price of IBM, or the best-selling DVD according to Amazon.com, you can write a short Script to Gather That Data IN A Format You Can Easily Manipulate. From A Developer's Perspective, It's as if you're Calling a local function That Returns a value.

A major advantage of web services is ubiquity across platforms and languages. A PHP script running on Linux can talk to an IIS server on a Windows box using ASP without any communication problems. When the server switches over to Solaris, Apache, and JSP, everything Transitions without a glitch.

SOAP is the most popular web services format. It's a W3C standard for passing messages across the network and calling functions on remote computers. This article shows how to create a SOAP client in PHP. The examples below demonstrate how to query Amazon's SOAP server to pull data from their site onto yours. from there, you can include a listing of newly released books on PHP on your web site, gather information about your CD collection, or even make a customized wedding registry site. The options are only limited by your imagination And Amazon's Lawyers.

For A More Detailed Introduction To Web Services, See Venu Vasudevan's Web Services Primer on Xml.com. Xml.com Also Has An Article Where Don Box Deconstructs SOAP, CALLED INSIDE SOAP.

. PHP does not come with a bundled SOAP extension Before you can begin, you need to download and install files that let you easily integrate SOAP into your applications There are three major SOAP implementations for PHP:. PEAR :: SOAP, NuSOAP, and PHP -Soap. The First Two Have More Features, But They're Written In 100% PHP, So They're Slowish. (NOT SLOW, MIND You, Just Slowish. They're Perfectly Fine for Medium-Traffic Sites.) PHP- SOAP, however, is written in C, so it's much faster That said, in this case, I prefer comprehensiveness and correctness over speed;. therefore, I use PEAR :: SOAP because it's simple to install and works for me.If pear, The pear package manager, is installed on your machine, Run the following command in your shell:

% PEAR Install SOAP

This will download, unzip, and install PEAR :: SOAP. Depending on which packages you've yet to install, you may get an dependency error. That means SOAP relies upon another package, like Net_URL, to handle some aspect of its business, But you don't have this package on your machine. if this happens, you'll see a message similar to this:

Downloading SOAP-0.7.3.tgz ...

... DONE: 73, 630 BYTES

Requires package `net_url '

SOAP: DEPENDENCIES FAILED

Solving the problem: Just Enter:

% Pear Install Net_URL SOAP

Now, pear will first install Net_URL and then SOAP. If a different package name is printed, substitute that name for Net_URL. If pear echoes multiple dependencies, place all of the package names on the command line before SOAP. (Depending upon your configuration, ......................... ..

Next, you need to head over to Amazon's web services site to download their developer's kit and apply for a developer's token. The application requires you to agree to a set of legal restrictions, such as not bombarding Amazon's servers with requests or using their data to construct a store that lets you buy things from Barnes and Noble.Amazon's developer archive contains a series of folders containing example code and applications in a several languages, including PHP, Java, Visual Basic, and even XSL. Right now, you're not going to use any of the files, but they'll come in handy in the future. As Amazon offers many different ways of searching and sends back lots of information, the complete API documentation is a much-needed reference.

Whew! Now that you've completed the set up, you can move on to the fun stuff. As I said in the introduction, with SOAP you can make requests of Amazon.com's database just as if you're calling a local function. you just need to know what function to call and what parameters to pass it. For example, to find all the books published by O'Reilly, you make a ManufacturerSearchRequest (). A KeywordSearchRequest (), on the other hand, is used to find everything written about PHP (Searches are not restricted to books, you can search for anything sold on Amazon:. music, DVDs, electronics, software, and even kitchen supplies). A full list is included in the documentation.

In PHP Using Pear :: Soap, Here's The Code To Find All of O'Reilly's Books Sorted from Best-Selling To Worst-Selling:

Require_once 'SOAP / Client.php';

$ wsdl_url =

'http://soap.amazon.com/schemas3/amazonwebservices.wsdl';

$ Wsdl = new soap_wsdl ($ WSDL_URL); $ client = $ wsdl-> getProxy ();

$ params = array (

'Manufacturer' => "O'Reilly",

'Mode' => 'Books',

'sort' => ' title',

'Page' => 1,

'Type' => 'Lite',

'tag' => 'trachtenberg-20',

'devtag' => 'xxxxxxxxxxxxx',

);

$ books = $ client-> manufacturersersearchrequest ($ params);

The first line loads in PEAR :: SOAP's client classes. This let you make SOAP requests to other servers. If you have trouble loading the files, make sure your include_path contains the folder where PEAR files are stored.

Then, you use WSDL (Web Services Definition Language) to create an object whose methods are the different functions Amazon understands. WSDL is a particularly cool part of web services. Not only does it let you manipulate an object as you would a PHP class, it even knows what parameters each method takes and each parameter's type Since unlike PHP, SOAP is a strictly typed language;. this allows PEAR :: SOAP to coerce variables into the appropriate types Amazon expects to receive, without any action on your part.

You first instantiate a new SOAP_WSDL object by passing $ wsdl_url, the location of Amazon's WSDL file, to the constructor. Next, SOAP_WSDL :: getProxy () is called, and it returns a client object, $ client. This is what you use to Make SOAP REQUESTS.

Now that the object is up and running, there's still the matter of making the actual ManufacturerSearchRequest () query. This method takes a few arguments, which are passed in as an (associative) array. Parameter names are the array's keys, and their values are the, well, array values.Parameters like manufacturer and mode control what you're searching for - in this case -. books manufactured by O'Reilly The sort, page, and type options specify what data is to be returned.

RESTS CAN OPTIONALLY Be Ordered from Best- To Worst-Selling, Alphabetical, by Price, And More.

in Front of

Salesrank Means Ordered from Best-Sell;

-Salesrank Reverses the Order.) To Conserve Resources, Amazon Only Returns Ten Items Per Request. Setting

Page to

1 means return books 1 THROUGH 10;

page

2 HAS Books 11 THROUGH 20; Ando Forth. If you want more tour, just create a loop and increment

Page Each Time THROUGH. Also, Since Amazon Has So Much Information, They've Created Two Different Dtds That Specify What Information They'll Return:

Lite and

Heavy. here, you get the

LITE RESULTS, WHICH HAVE The Product Name, Author, Price, Three Different Image Urls, and The Manufacturer. The

Heavy DTD HAS Everything, Any Listmania Lists Containing The Work, And Links To Music Clips for CDS.

Also, You Pass IN A Tag and A Devtag. The Tag IS An Amazon Associate Name, SO You Can Collect Referral Fees. The devtag is the development's token you receivers.

You do not need to worry about the parameter order. That's all taken care of for you behind the scenes. That's not all that's done behind closed doors, however. When you finally make the request, by calling $ client-> ManufacturerSearchRequest ($ params), PEAR:.. SOAP converts your PHP data structures to a SOAP message written in XML and sends an HTTP request to Amazon's server After Amazon receives and processes your query, it replies with a SOAP message of its own PEAR :: SOAP listens for this response and parses the XML into a PHP object, which is then returned by our method and stored in $ books.When you're unsure what's in a variable, the easiest way to inspect it is to use print_r (). Calling print_r ($ books) echoes:

Stdclass Object

(

[TotalResults] => 822

[Totalpages] => 83

[Details] => array

(

[0] => stdclass object

(

[URL] => http://www.amazon.com / ...

[Asin] => 0596004478

[ProductName] => Google Hacks

[Catalog] => BOOK

[Authors] => array

(

[0] => Tara Calishain

[1] => Rael Dornfest

)

[Releasedate] => 01 February, 2003

[Manufacturer] => O'Reilly & Associates

[Imageurlsmall] => http://images.amazon.com / ...

[Imageurlmedium] => http://iMages.amazon.com / ...

[Imageurllarge] => http://images.amazon.com / ...

[Listprice] => $ 24.95

[Urprice] => $ 17.47

[USEDPRICE] => $ 15.95

)

INSERT NINE Additional Books Here]

)

)

The object has three properties: TotalResults, the number of items that the search matches; TotalPages, the number of times you need to increment $ page and requery Amazon to gather all the data; and Details, an array containing the actual catalog information Each. element of Details is itself another array, with the properties you can use to do things like making your own Amazon store or printing information about the pile of books next to your bed. (I've shortened some of the data so it fits nicely in For example, here's a quick-and-dirty loop to create html showing the book title, author (s), and price next to a jpeg picture of the cover:

Foreach ($ HITS-> Details AS $ HIT) {

$ ProductName = HTML_ENTITIES ($ HIT-> ProductName);

$ Authors = join ('and', $ hit-> authors);

Print <<< _html_

>

$ productName

BY $ authors

Amazon.com Price: $ HIT-> Ourprice

_Html_;

}

This iterates through $ hits :: Details and places each book inside of its own

. (Of course, a cleaner solution is to place the style information in a class instead of embedding it inside of each
.) Within the loop, you can pull out the data you want to show. If it's already formatted how you like, print it directly. Or, if it needs a little massaging, like the authors array, reformat it, as is done above by calling join ( ). You Also need to call html_entities () on ProductName and Other text Fields, Because You need to encode Characters Like the & in O'Reilly & Associates.you Can See The Results in Figure 1.

Figure 1. Reformatted Book Data from The Amazon Database

Amazon also allows more complex queries that filter the listings on multiple criteria You can use PowerSearchRequest () with Boolean logic to construct a search For example, to restrict your O'Reilly search to only books on PHP..:

$ params = array (

'Power' => "Publisher: O'Reilly and keywords: PHP",

'Mode' => 'Books',

'sort' => ' title',

'Page' => 1,

'Type' => 'Lite',

'tag' => 'trachtenberg-20',

'devtag' => 'xxxxxxxxxxxxx',

);

$ Hits = $ Client-> PowerSearchRequest ($ Params);

Only the first array element has changed It's now power instead of manufacturer Also, its value, publisher:.. O'Reilly AND keywords: PHP, makes sure that the publisher is O'Reilly AND that the book is on PHP You can also. Use OR and NOT AS WELL As Group Expressions Using (PARENTHESIS).

Now, The Same Display Function Generates New Output:

Figure 2. A Filtered SearchConclusion

As you've seen, it's very simple to use SOAP and WSDL with PHP. These clients allow you to gather information from across the net to use in your scripts. Amazon.com is not the only major company to provide a SOAP front end to ITS Data. Google Lets You Search Their Listings Up to 1,000 Times A Day. Additionally, Xmethods Has A Large Directory of Soap Servers That You Can Experiment with and use.

Adam Trachtenberg is a Technical Evangelist for eBay and the author of two O'Reilly books: Upgrading to PHP 5 and PHP Cookbook He will be speaking at OSCON in July 2004 on "Why PHP 5 Sucks Why PHP 5 Rocks !,!" ". PHP 5 MySQL 5 = a Perfect 10, "AND" PHP 5 Bootcamp for PHP 4 Programmers.

转载请注明原文地址:https://www.9cbs.com/read-123628.html

New Post(0)
CopyRight © 2020 All Rights Reserved
Processed: 0.051, SQL: 9