Custom Google Search Results For Your Website Using PHP

Custom Google Search Results For Your Website Using PHP Posted June 13, 2009 @ 11:55pm by Phil

With the recent launch of the new Microsoft search engine Bing, I wanted to see what kind of things were possible with the accompanying API. Within a few minutes, I discovered it would be possible to create a kick ass custom search for this site using JSON (like XML, only smaller). Unfortunately, after some implementation, I noticed that Bing had only searched one page of my site. Still wanting a kick ass custom search, I decided to see what mother Google could bring to the table. I recall a few years ago trying to build a custom search with Google to be quite troublesome. Pleasantly surprised, I found that Google offered the same functionality as Bing, and I was able to quickly adapt my solution for Google. Here it is:

<?php
  function google_query ($query)
  {
    $http_host = $_SERVER["HTTP_HOST"];
    $query_encoded = urlencode("site:$http_host $query");
    
    $content = file("http://ajax.googleapis.com/ajax/services/search/web?rsz=large&v=1.0&q=$query_encoded");
    
    $json = json_decode($content[0], true);
    
    $results = array();
    foreach ($json["responseData"]["results"] as $result)
    {
      if ($result["GsearchResultClass"] == "GwebSearch")
      {
        $results[] = array("title" => $result["title"], "url" => $result["url"], "content" => $result["content"]);
      }
    }
    
    return $results;
  }
?>

Download Source: google_query.php

Short and sweet. This function queries the Google search results and returns a nice associative array.

Note: If you are still using a version of PHP lower than 5.2.0, you will probably need to use Mike Migurski's JSON Library and do a little bit of code modification.

You probably won't notice an actual search feature on this site for a little bit. I still need to figure out where to put the search bar, and it isn't like my site needs search capabilities right now anyway. I also found out that my search results look like crap, so I am making some changes to pretty those up a bit.

Tags: PHP/MySQL, Webmasters Tips