PHP

Page 212

XML and Web Services ” 193

ment that describes the function calls made available by a Web service, as well as any specialized data types needed by it.

Accessing SOAP-based Web Services The SoapClient class provides what is essentially a one-stop solution to creating a SOAP client—all you really need to do is provide it with the path to a WSDL file, and it will automatically build a PHP-friendly interface that you can call directly from your scripts. As an example, consider the following SOAP request made to the Google Web Search service: try { $client = new SoapClient(’http://api.google.com/GoogleSearch.wsdl’); $results = $client->doGoogleSearch($key, $query, 0, 10, FALSE, ’’, FALSE, ’’, ’’, ’’); foreach ($results->resultElements as $result) { echo ’<a href="’ . htmlentities($result->URL) . ’">’; echo htmlentities($result->title, ENT_COMPAT, ’UTF-8’); echo ’</a><br/>’; } } catch (SoapFault $e) { echo $e->getMessage(); }

This creates a new SOAP client using the the WSDL file provided by Google. SoapClient uses the WSDL file to construct an object mapped to the methods defined by the web service; thus, $client will now provide the methods doGetCachedPage(), doSpellingSuggestion(), and doGoogleSearch(). In our example, the script invokes the doGoogleSearch() method to return a list of search results. If SoapClient encounters any problems, it will throw an exception, which we can trap as explained in the Object-oriented Programming in PHP chapter). The constructor of the SOAPClient class also accepts, as an optional second parameter, an array of options that can alter its behaviour; for example, you can change the


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.