Using the Google API

| Comments
Google cancels API

As of December 2006, Google no longer issues SOAP API keys. If you’re looking for a search API, you might want to try MSN’s API, or use Google’s AJAX api’s. This post remains for historical reasons only.

In another article we discussed the MSN Search API, presenting a PHP class to allow easy use of MSN Search. But what if you want to use the Google API instead of MSN? One advantage of object-oriented programming is the class functions as a “black-box”; the user of the code unaware of how it does it’s job so MSN’s API can be swapped with Google’s, Yahoo’s, or any other. All you have to do is modify the search() function for Google, and then the previous code works for Google’s API.

Warning!

You should *never* try out code on your production server. Always have a test or development box for trying out new code. Experimenting on your live server is asking for trouble!

Before continuing, review the MSN Search API article as it contains important information about how SOAP works, character set issues with SOAP and UTF-8, and explains how the class works. This article assumes you’ve read the background, and downloaded the code included on that page. All we need to do is make a few changes and the MSN class works with Google. Best of all, since all the SOAP calls are encapsulated in the class, the end-user search page needs virtually no changing.

Here’s the updated search() function to use with Google’s API. The rest of the class is the same as the MSNSearch class. You can download the complete GoogleSearch class or just make the changes noted below to the MSNSearch class.

function search() {
  $this->errorMessage = "";
  $this->totalPages = 0;
  $this->totalRecords = 0;
  $this->results = array();
  $parameters = array(
    'key' => $this->appID,
    'q' => $this->query, 
    'start' => ($this->page - 1) * $this->recordsPerPage,
    'maxResults' => 10,
    'filter' => false,
    'restrict' => '',
    'safeSearch' => ($this->safeSearch ? true : false)
    'lr' => '',
    'ie' => 'UTF-8',  # No longer used by google - ignored
    'oe' => 'UTF-8'  # No longer used by google - ignored
  );
  $soapClient = new soapclientx('http://api.google.com/search/beta2');
  $retry_count = 0;
  $soapResult = false;
  while( !$soapResult && $retry_count < 3) {  # Try request 3 times before failing
    $soapResult = $soapClient->call('doGoogleSearch', $parameters, 'urn:GoogleSearch');
    $retry_count++;
  }
  if ($soapClient->getError()) {
    $this->errorMessage = $soapClient->getError();
    $msg = "Search error:\n" . $this->errorMessage . "\n";
    $msg .= "Query: " . $this->query . "\n";
    $msg .= "Date: " . date('D M d Y h:i:s');
    if (defined("MAILTO"))
      @mail(MAILTO,"** Search ERROR ***", $msg);
    return false;
  }
  $this->totalRecords = $soapResult['estimatedTotalResultsCount'];
  $this->totalPages = ceil($this->totalRecords / $this->recordsPerPage);
  if (($this->totalRecords > 0) && (is_array($soapResult['resultElements']))) {
    foreach ($soapResult['resultElements'] as $item) {
      $this->results[] = array (
        'url' => $item['URL'],
        'displayurl' => $item['URL'],
        # Google doesn't have cache URL's, but provides other API's for fetching from Google cache.
        # As a result, cacheurl will always be empty. For compatability with MSNSearch class, it's
        # left in the result set.
        'cacheurl' => isset($item['CacheUrl']) ? $item['CacheUrl'] : "",
        'title' => isset($item['title']) && trim($item['title']) != '' ? $item['title'] : $item['URL'],
        'snippet' => isset($item['snippet']) ? strip_tags($item['snippet']) : ""
      );
    }
  }
  return true;
}

Just replace the search() function in the MSNSearch class with this code, and rename the class from MSNSearch to GoogleSearch in two places. That’s almost all that needs to be done. Google search API has one issue you’ll have to deal with — it can return HTML in the snippet which may invalidate your nice XHTML page. Thus, we use the strip_tags() function to remove any HTML in the snippet.

You now have a class to use with the Google search API. The complete GoogleSearch class is available to download, but you’ll need the NuSOAP class and the end-user search page from the MSNSearch article already mentioned.

The search form just needs a change from using the MSNSearch class to using the GoogleSearch class we just created. The complete PHP code is available on the previous MSN Search API article; below is the change required.

<?php
print searchform($q,"form_top",SEARCH_URL);
if (strlen($q) > 1) {
  $googlesearch = new GoogleSearch('INSERTAPIKEYHERE');
  $sresult = false;
  $googlesearch->setQuery($q);
  $googlesearch->setPage($start);
  $sresult = $googlesearch->search();
  if (($sresult === true) && ($googlesearch->totalRecords > 0)) {
    print $googlesearch->search_header($q);
    print $googlesearch->search_results();
    print $googlesearch->search_navagation($q);
    print searchform($q,"form_bottom",SEARCH_URL);
  } else 
    print "<p>Sorry, no results found for <b>$q</b>.</p>\n";
} else { ?>
<p>Enter the terms you wish to search for above.</p>
<?php } ?>

You’ll need a Google API Key to put in where it says INSERTAPIKEYHERE. One other change you need to make is at the top of the file on the line that includes the search class. Find the line include ($_SERVER[’DOCUMENT_ROOT’] . “/include/MSNSearch.php”); and change it to read include ($_SERVER[’DOCUMENT_ROOT’] . “/include/GoogleSearch.php”);.

That’s it! You now can use either MSN’s or Google’s API’s to search. By changing the search() function, you could use any search method you want, without changing your end-user search page.

Like this article? Stay up to date with new articles and content. It’s free, and we won’t sell your information.
SIGN UP TODAY by entering your primary email address below to guarantee you won’t miss anything.

Site Updates

Want new posts delivered to your inbox? Enter your email address to get FREE emailed updates!

More information...

Other ways to stay current: