Programming the Google Web API with PHP

screenshot moderate.gifscreenshot tip55.gif

A simple example of coding the Google Web API with PHP and the NuSOAP module.


PHP (http://www.php.net/), a recursive acronym for "PHP Hypertext Processing," has seen wide use as the HTML-embedded scripting language for web development. Add to that the NuSOAP PHP module for creating and consuming SOAP-based web services (http://dietrich.ganx4.com/nusoap) and you've a powerful combination.

This tip illustrates basic use of PHP and NuSOAP in concert to interact with the Google Web API.

The Code

«!--
# googly.php
# A typical Google Web API php script
# Usage: googly.php?query=«query»
--»
«html»
«head»
 «title»googly.php«/title»
«/head»
«body»
«?
# Use the NuSOAP php library require_once('nusoap.php');
# Set parameters
$parameters = array(
 'key'=»'insert key here',
 'q' =» $HTTP_GET_VARS['query'],
 'start' =» '0',
 'maxResults' =» '10',
 'filter' =» 'false',
 'restrict' =» '',
 'safeSearch' =» 'false',
 'lr' =» '',
 'ie' =» 'latin',
 'oe' =» 'latin'
);
# Create a new SOAP client, feeding it GoogleSearch.wsdl on Google's site
$soapclient = new soapclient('http://api.google.com/GoogleSearch.wsdl', 'wsdl');
# query Google
$results = $soapclient-»call('doGoogleSearch',$parameters);
# Results?
if ( is_array($results['resultElements']) ) {
 print "«p»Your Google query for '" . $HTTP_GET_VARS['query'] . "' found " 
. $results['estimatedTotalResultsCount'] . " results, the top ten of which 
are:«/p»";
 foreach ( $results['resultElements'] as $result ) {
 print 
 "«p»«a href='" . $result['URL'] . "'»" . 
 ( $result['title'] ? $result['title'] : 'no title' ) .
 "«/a»«br /»" . $result['URL'] . "«br /»" .
 ( $result['snippet'] ? $result['snippet'] : 'no snippet' ) .
 "«/p»";
 }
}
# No Results else {
 print "Your Google query for '" . $HTTP_GET_VARS['query'] . "' returned no results";
}
?»
«/body»
«/html»

Running the Tip

Invoke this tip from your browser in the same manner you would a CGI script. It accepts one named argument, query with your preferred Google search:

http://localhost/googly.php?query=your google query

The Results

A search for php looks something like Figure 5-1.

Figure 5-1. PHP results page
screenshot google-tips-0501.gif