HomePHP Page 6 - Using The Google Web APIs With PHP
The Sum Of All Parts - 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.
Thus far, the two examples you've seen have had the search term hardwired into them. Needless to say, this isn't very useful in the real world - it's far more sensible to have the search term generated dynamically via user input. The next example does just that, demonstrating how you can add a full-fledged, Google-backed search engine to your application.
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Search term: <input type="text" name="q">
// include the class
// create a instance of the SOAP client object
$soapclient = new
// 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
'q' => $_POST['q'], // search
'start' => 0, // start
from result n
'maxResults' => 10, // show a
total of n
'filter' => true, // remove
'restrict' => '', // restrict
'safeSearch' => true, // remove
'lr' => '', // restrict
'ie' => '', // input
'oe' => '' // output
// invoke the method on the server
$result = $soapclient->call("doGoogleSearch", $params,
// print the results of the search
<? echo $result['faultstring'];?>
Your search for <b><?=$result['searchQuery']?></b>
produced <?=$result['estimatedTotalResultsCount']?> hits.
foreach ($result['resultElements'] as $r)
echo "<li><a href=" . $r['URL'] . ">" .
$r['title'] . "</a>";
echo $r['snippet'] . "(" .
$r['cachedSize'] . ")";
As you can see, this script is split into two sections, one
for the search form and the other for the search results. An "if" statement, keyed on the presence or absence of the query string, is used to decide which section of the script to execute.
// display form
// execute query on Google
Here's what the search form looks like:
Once the user enters a search term and submits the form, the second half of the script springs into action, initializes the SOAP client and performs the query on the Google SOAP server. The result is then formatted and displayed as in the previous example. Here's an example of what it might look like:
And there you have it - your very own Google search!