Using The Google Web APIs With PHP - The Sum Of All Parts (
Page 6 of 9 )
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.
<html>
<head><basefont face="Arial"></head>
<body>
<?php
if (!$_POST['q'])
{
?>
<h2>Search</h2>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Search term: <input type="text" name="q">
</form>
<?
}
else
{
// 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' => $_POST['q'], // 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' => '', // 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 ($result['faultstring'])
{
?>
<h2>Error</h2>
<? echo $result['faultstring'];?>
<?
}
else
{
?>
<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>
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.
<?php
if (!$_POST['q'])
{
// display form
}
else
{
// 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!