Using The Google Web APIs With PHP - Chasing Liberty (
Page 5 of 9 )
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:
<html>
<head><basefont face="Arial"></head>
<body>
<?php
// include the class
include("nusoap.php");
// 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
key
'q' => 'liberty equality fraternity', // search term
'start' => 0, // start from result
n
'maxResults' => 10, // show a total of n
results
'filter' => true, // remove similar
results
'restrict' => '', // restrict by topic
'safeSearch' => true, // remove adult
links
'lr' => 'lang_en|lang_fr', // restrict by
language
'ie' => '', // input encoding
'oe' => '' // output encoding
);
// invoke the method on the server
$result = $soapclient->call("doGoogleSearch", $params,
"urn:GoogleSearch", "urn:GoogleSearch");
// print the results of the search
// if error, show error
if ($result['faultstring'])
{
?>
<h2>Error</h2>
<? echo $result['faultstring'];?>
<?
}
else
{
// else show list of matches with links
?>
<h2>Search Results</h2>
Your search for <b><?=$result['searchQuery']?></b> produced
<?=$result['estimatedTotalResultsCount']?> hits.
<br>
<ul>
<?
if (is_array($result['resultElements']))
{
foreach ($result['resultElements'] as $r)
{
echo "<li><a href=" . $r['URL'] . ">" .
$r['title'] . "</a>";
echo "<br>";
echo $r['snippet'] . "(" . $r['cachedSize'] .
")";
echo "<p>";
}
}
?>
</ul>
<?
}
?>
</body>
</html>
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.