Web Development

Using the Google Web API with PHP

Adding a Google Search to Your Site

Unless you are stubborn or completely out of touch with reality you should be aware that Google provides the best search results for websites. Search functionality plays an integral role in the user experience for many sites. We will be looking at 3 different options. Two of these you can start using commercially. The other is currently in beta and not for commercial use. Nonetheless, you’ll be able to have Google’s search results on your website after finishing this article.

Keep It Simple (and Free)

Google offers a Free Search feature to use on third party websites. This allows you to utilize Google’s by narrowing the search results to a particular set of domain(s). With this service you are able to place your logo at the top of a page served by Google’s server. Google also supplies the HTML needed to place a search box anywhere on your site. To implement this search feature into your website you simply need to register for the free service. You can do this at the following URL: http://services.google.com/cobrand/free_trial.

Customizations? It’ll Cost You

If the previous method didn’t provide enough flexibility, then you can upgrade to the Silver or Gold Search. This has all of the functionality as the free Google Free Search with some additional features. The Gold and Silver Search account allows you to place custom HTML at the top and bottom of the search results page. This would allow you to not only place your logo on the page but you could also include your site navigation as well as advertising banners. You can also view monthly reports that include the number of search queries performed per day. You can sign up for a Silver or Gold Search at the following URL: http://www.google.com/services/silver_gold.html.

The Elusive Google Web API

The third method allows by far the most customization. However, this method is still in beta and can’t really be used on sites, which generate a lot of searches. Importantly, this feature cannot be used for commercial use. The Google Web API allows developers to utilize Google’s search on a number of platforms including Java, .NET, and any platform that supports web services. Let’s have a look at what we need in order to get started. Here is an introduction into how to get started: http://www.google.com/apis/.

Once you have signed up and received your license key you can begin testing. The developer’s kit contains some very useful files which you should have a look through at your own leisure. We are going to proceed as if you are already somewhat familiar with the contents of the kit (which won’t be completely necessary to complete our example).

Taking a Look Inside

Let’s take a look at the process we are going to use to retrieve search results from Google and get them onto our website. We will be doing this as a web service. WSDL, SOAP, and UDDI form the foundation standards of web services. We will be using SOAP and WSDL. The details of web services are beyond the scope of this article since we will only be working with a very basic example. We will also be using NuSOAP, thus, you should download the newest version at http://dietrich.ganx4.com/nusoap/. An overview of what is going to happen is:

1 – Include the NuSOAP class

2 – Create a soapclient object

3 – Define an array of search criteria

4 – Make a SOAP request to Google

5 – Display the results returned

Lubing the Chains

Let’s get started with the code and include NuSOAP.

<?php
  include 'nusoap.php';
?>

The second step is to create a soapclient object. This is defined in class.soapclient.php and it is required automatically by nusoap.php so you don’t have to make any further inclusions. We are going to pass two parameters to the soapclient constructor. The first parameter is the URL to the webservice we are going to be using. The second parameter will specify that we are using WSDL. The code to create the soapclient object will look like this:

$soapclient = new soapclient("http://api.google.com/GoogleSearch.wsdl","wsdl");

The next step will be to build an array of parameters to specify the search criteria. We are going to define an associate array using the keys as the parameter name and the values as the parameter value. Looking at the GoogleSearch.wsdl file from the developer’s kit will tell us which parameters we can pass along with our SOAP request. We will be calling the doGoogleSearch method so let’s locate that methods definition. The section we’re interested in looks like so:

  <message name="doGoogleSearch">
    <part name="key"            type="xsd:string"/>
    <part name="q"              type="xsd:string"/>
    <part name="start"          type="xsd:int"/>
    <part name="maxResults"     type="xsd:int"/>
    <part name="filter"         type="xsd:boolean"/>
    <part name="restrict"       type="xsd:string"/>
    <part name="safeSearch"     type="xsd:boolean"/>
    <part name="lr"             type="xsd:string"/>
    <part name="ie"             type="xsd:string"/>
    <part name="oe"             type="xsd:string"/>
  </message>

For this example we are going to specify a value for each parameter listed above. Our criteria array would look something like this:

  $params = array('key'         => 'YOUR_GOOGLE_KEY',
                  'q'           => 'site:php.net updates',
                  'start'       => 0,
                  'maxResults'  => 10,
                  'filter'      => false,
                  'restrict'    => '',
                  'safeSearch'  => false,
                  'lr'          => '',
                  'ie'          => '',
                  'oe'          => ''
                  );

This array specifies that the search results should include pages from the php.net website and contain the keyword “updates”. We should receive search results starting from 0 and ending at 10. We have also omitted any filters, restrictions, and safesearch.

Now we are ready to make our search request. We will be using the “call” method of our soapclient object and passing two parameters. The first parameter we want to invoke is the webservice’s method that we mentioned above. Remember, it is called doGoogleSearch. The second parameter we are going to pass is our search criteria array. The code to invoke the call method and save the response to a local array variable would look like this:

  $result = $soapclient->call("doGoogleSearch", $params);

This will give us access to the search results via the multi-dimensional array $result. We can look at the GoogleSearch.wsdl file once again to see what type of data they have so kindly returned to us. The first thing we are going to do is to look and see how many results matched our search criteria. You may have noticed that there is a key in our array named estimatedTotalResultsCount. If we have more than 0 results we can loop through the results to display them. All of the data we are going to be accessing is defined in the GoogleSearch.wsdl file. Our display code will look like this:

if($result['estimatedTotalResultsCount'] > 0)
{
  echo "Displaying {$result['estimatedTotalResultsCount']} result(s)<br /><br />";
   foreach($result['resultElements'] as $v)
   {
   $title      = $v['title'];
   $url        = $v['URL'];
   $snippet    = $v['snippet'];
   echo "<a href="{$url}">{$title}</a><br />{$snippet}<br /><br />";
   }
 }
else
 {
    echo 'Sorry but there are no search results that matched your criteria';
}

That will display the number of search results followed by each result found. The title of the page will be linked to the URL. Below the link will be the snippet identical to the snippet you see on Google’s search results page.

That is all you need to implement use of the Google Web API on your site using PHP and SOAP. An important note to be aware of is that each license key enables you to perform 1000 queries per day. This service is also in beta still and Google reserves the right to change the way it’s implemented.

About the author

Written by Jaisen Mathai.

If you found this post useful you may also want to check these out:

  1. Applying CSS to Forms
  2. Creating a Drop Down Selection with an Array
  3. How To Send Email With Perl, Part III
  4. Adding records to a MySQL database using PHP
  5. 5 Steps To Successful SEO And E-commerce
  6. Publishing Newsletters Using PHP & MySQL – 4