HomePHP Page 5 - Using The Google Web APIs With PHP
Chasing Liberty - PHP
The Google Web APIs allow developers to build SOAP-basedapplications driven off Google's unique indexing and searchcapabilities. And since there are now quite a few PHP classes designedfor SOAP transactions over HTTP, integrating the two has never beensimpler. This article explains how.
If you take a close look at the output of the previous example, you'll see that the call to doGoogleSearch() results in a PHP associative array containing a series of result elements, together with some statistics on the search itself. It's extremely simple to use this array to create an HTML page containing a properly-formatted list of matches to the query term. Here's an example:
// include the class
// create a instance of the SOAP client object
$soapclient = new soapclient("http://api.google.com/search/beta2");
// uncomment the next line to see debug messages
// $soapclient->debug_flag = 1;
// set up an array containing input parameters to be
// passed to the remote procedure
$params = array(
'key' => 'your-google-license-key-xxxxxxxx', // Google license
'q' => 'liberty equality fraternity', // search term
'start' => 0, // start from result
'maxResults' => 10, // show a total of n
'filter' => true, // remove similar
'restrict' => '', // restrict by topic
'safeSearch' => true, // remove adult
'lr' => 'lang_en|lang_fr', // restrict by
'ie' => '', // input encoding
'oe' => '' // output encoding
// invoke the method on the server
$result = $soapclient->call("doGoogleSearch", $params,
// print the results of the search
// if error, show error
<? echo $result['faultstring'];?>
// else show list of matches with links
Your search for <b><?=$result['searchQuery']?></b> produced
foreach ($result['resultElements'] as $r)
echo "<li><a href=" . $r['URL'] . ">" .
$r['title'] . "</a>";
echo $r['snippet'] . "(" . $r['cachedSize'] .
Most of this is identical to what you saw in the previous
example, except that, this time, instead of just dumping the result array to the screen, I've used a "foreach" loop to iterate through it and display the matches as items in a bulleted list. Note how the various keys of the SOAP response array can be used to build the list of matching Web pages, with descriptions and URLs.
In the event that the procedure generates an error on the server, the response array will contain a SOAP fault. It's generally considered good programming practice to check for this and handle it appropriately - you'll see that I've done this in the script above.