Adding Google Business search to your ecommerce website

July 19, 2007

The internet is abuzz with news of Google's new business custom search engine. Google is allowing business sites to have their own custom search engine for $100 per year (<5,000 pages) or $500 per year (up to 50,000) pages. This includes some cool reporting and an XML API so that you can customize to your heart's content.

Google Custom Search

After messing around with Google's javascript code I decided to write my own little script to better integrate it into my website. The javascript code was giving me some major problems with the width of my pages, so I canned it and went to their XML version of the search function.

The following is a very simple php & html script that you can use for your own Google business search engine. It was made for a php5 server as it uses the built-in simpleXML class. Save this in a separate file, configure one or two lines based on your Google search account, use php to include it between in the body of your site, and that's it.

It currently uses two tables, but you can easily change this to a division based layout. I used tables only so I didn't have to use external css, or mess with division styling that might not work universally. Also, you can post to this page from a form anywhere on your site as long as the text field is names query and you are using the GET method to submit the form. Lastly, I would set error_reporting to E_ERROR, as E_WARNING may generate some few warnings.

Here we go:

The zip file has a version with correct tabs and the GPL license and is located below this code. Also, I rarely distribute code that I write, so I apologize in advance for any poor commenting.

Save this file as googleSearch.php or something similar. Edit the $accountId variable with your information, and change the form action="" to the page on your site that you will include this file on (IE: The actual search page you want to use on the site: search.php, site-search.php, etc.).

PHP:
  1. <!-- Start Search Box -->
  2. <table width="100%" border="0" cellspacing="0" cellpadding="10">
  3.   <tr>
  4.     <td align="center" valign="middle">
  5.    
  6.     <form action="site-search.php">
  7.         <input name="query" type="text" size="40" value="<?php if(isset($_GET['query'])){echo urldecode(cleanSearch($_GET['query']));} ?>" />
  8.         <input type="submit" name="sa" value="Search" />
  9.         <img src="http://google.com/coop/images/google_custom_search_smnar.gif" alt="Google Custom Search" />
  10.    </form>
  11.    
  12.     </td>
  13.   </tr>
  14. </table>
  15. <!-- End Search Box -->
  16.  
  17. <?php
  18.  
  19. //constants
  20. $accountId = ''; //put google search ID Here - Should be a long string of numbers letters and symbols
  21. $collation  = 'ISO-8859-1'; //change this if you want something other than ISO-8859-1, IE: ut8-f
  22. $numberPerPage = '10'; //this is how many results you want per page
  23. $noResults = 'There were no results found for your search. Please try again.'; //Message if no results are found
  24.  
  25. //check if the form was submitted
  26. if(!empty($_GET['query'])){
  27.    
  28.     //clean the input so that it is safe
  29.     $searchTerm = cleanSearch($_GET['query']);
  30.    
  31.     //cast $_GET['start'] to an integer just in case
  32.     $start = (int)$_GET['start'];
  33.    
  34.     //build the google query here
  35.     $buildQuery = 'http://www.google.com/search?cx='.$accountId.'&client=google-csbe&start='.$start.'&num='.$numberPerPage.'&output=xml_no_dtd&q='.$searchTerm.'&ie='.$collation.'&oe='.$collation;
  36.    
  37.     //get the result for the query from google
  38.     $thisSearch = file_get_contents("$buildQuery");
  39.    
  40.     //instantiate a simple xml class and process the google result
  41.     $xml = new SimpleXMLElement($thisSearch);
  42.    
  43.     //find the number of results for pagination later on
  44.     $total = count($xml->RES->R);
  45.    
  46.     //Display Nothing found message if there are no results.
  47.     if($total <1){
  48.    
  49.         $output .=  "<p>$noResults</p>";
  50.    
  51.     }
  52.    
  53.     //loop through the results
  54.     foreach ($xml->RES->R as $key){
  55.        
  56.         //the replaceChars removes anything you need it to, I found google returning some unusable characters, and you can fix it with this function
  57.         //Edit the actual find / replace at the bottom
  58.        
  59.         //format the output for each result
  60.         $output .=  '
  61.         <p><a href="'.$key->U.'">'.replaceChars($key->T).'</a><br />
  62.         '.replaceChars($key->S).'<br />
  63.         <span style="color:#060;">'.$key->U.'</span></p>
  64.         ';
  65.    
  66.     }
  67.    
  68.     //simple pagination
  69.     $output .= '
  70.     <table width="100%" border="0" cellspacing="0" cellpadding="5">
  71.         <tr>
  72.     ';
  73.         
  74.         //make sure we dont display previous page on the first page
  75.         if ($start> 0){
  76.        
  77.             $output .= '<td align="left"><a href="?query='.$searchTerm.'&start='.($start - $numberPerPage).'">&laquo; Previous 10</a></td>';
  78.        
  79.         }
  80.        
  81.         //make sure we dont display next page on the last page
  82.         if ($total == $numberPerPage){
  83.            
  84.             $output .= '<td align="right"><a href="?query='.$searchTerm.'&start='.($start + $numberPerPage).'">Next 10 &raquo;</a></td>';
  85.                
  86.         }
  87.    
  88.     $output .= '
  89.         </tr>
  90.     </table>
  91.     ';
  92.    
  93.     echo $output;
  94.  
  95. }
  96.  
  97. function cleanSearch($input){
  98.     //this will clean the query so that it is safe to use for whatever
  99.     //this is broken into steps, but can be done on a single line if prefered
  100.    
  101.     //trim whitespace
  102.     $input = trim($input);
  103.    
  104.     //if you would like your users to be able to search for code, you can comment this out
  105.     //Make sure you know what you're doing before you comment this out!
  106.     $input = strip_tags($input);
  107.    
  108.     //Convert html characters to a safe format, IE: & - &amp; etc.
  109.     $input = htmlspecialchars($input);
  110.    
  111.     //convert to a url safe code since we use the GET function to request from google
  112.     $input = urlencode($input);
  113.    
  114.     return $input;
  115. }
  116.  
  117. function replaceChars($input){
  118. //using this function to replace some html from the data returned by google
  119. //Make sure there is a corresponding value in the find and replace arrays or you will have problems
  120.    
  121.     //these are what you want to replace
  122.     $find = array(
  123.     '»',
  124.     '<br>'
  125.     );
  126.    
  127.     //these are what you need to replace them with
  128.     $replace = array(
  129.     '&raquo;',
  130.     ''
  131.     );
  132.    
  133.     return str_replace($find,$replace,$input);
  134.  
  135. }
  136.  
  137. ?>

Example of how to implement it:

This is the actual page that you will submit to. Name it something like search.php and upload it with the googleSearch.php file to your server.

HTML:
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  4. <title>My Custom Search</title>
  5. </head>
  6.  
  7. <?php include "googleSearch.php"; ?>
  8. </body>
  9. </html>

Download this file along with it's license and correct tab layout. http://www.ecommerce-blog.org/googleSearch.zip

Related information:
Official Google Custom Search Blog
The Benefits of Using Google's Custom Search Engine - seobook.com
Google Custom Search Engine for Businesses - online-tech-tips.com

**If you notice any errors or security issues with any of the code, or bugs in general let me know and I will update this script.

Comments

19 Responses to “Adding Google Business search to your ecommerce website”

  1. Pilgrim’s Picks for July 20 | Marketing Pilgrim on July 20th, 2007 8:59 am

    [...] Ecommerce Blog has written a script to help you add the new custom Google business search to your [...]

  2. Getting into Google Custom Business Search » eCommerce Cache :: Varien eCommerce Blog :: A blog focused on the design, marketing, and implementation of online commerce on July 20th, 2007 1:59 pm

    [...] eCommerce Blog has posted a simple script to help you add a Google business search engine to your own [...]

  3. jestep on September 18th, 2007 9:52 am

    Updated the script to add support for no results found. Sep 19, 2007

  4. toto on September 19th, 2007 7:56 am

    Do you have a example ?

  5. jestep on September 19th, 2007 7:59 am

    I’m using this script on my main business website here:
    http://www.merchantequip.com/

  6. joerge on October 2nd, 2007 11:08 pm

    hi,
    i found error on my search box :
    ” site-search.php was not found on this server.”

    and what a code site-search.php ? im found file on googleSearch.zip just ‘googlesearch.php’

    let me know

  7. jestep on October 3rd, 2007 9:00 am

    On this page, copy the bottom code box, paste it into an html file and name it site-search.php. The download has been updated as well.

  8. Bryan on November 20th, 2007 7:01 pm

    Being a complete beginner at PHP, I’ve been hoping to find a script just like yours so that I can add an XML implementation of Google Search to our company’s website. Unfortunately, our web host runs PHP 4 and we don’t have the option of upgrading. In trying to figure out why the script wasn’t working, I determined that SimpleXMLElement doesn’t exist in PHP 4, which I’m hoping is the only part of the script that is incompatible.

    Because I can’t find any other scripts that do this, it looks like I’ll have to get a book and learn PHP. I’m curious about one thing though: Is XML parsing in PHP4 similar enough to PHP5 that I’ll just be able to make some modifications to your script or is everything so different that I’ll have to try to rewrite the script from the ground up?

    Thanks,
    Bryan

  9. jestep on November 20th, 2007 9:51 pm

    You should definitely see if you host plans to upgrade their php, and try to get them to if they aren’t planning it. PHP4 is past its End of Life as php6 is just around the corner. They may also have servers with php5 on them that they can transfer your domain to with little difficulty.

    As far as using it with php4, I would look around for a php4 class that mimics the simpleXML class. If I come across one that looks decent, I’ll post it up here.

  10. Bryan on November 29th, 2007 3:02 pm

    First of all thanks for the tip. I was able to find a class that mimics PHP5’s SimpleXML here: http://www.criticaldevelopment.net/xml/. There was still some programming required to get your code to work with the class because the class is still not as easy as SimpleXML and “foreach” loops don’t work for objects in PHP 4, either, but I managed to get it up and running.

    Also, I wanted to let you know that I might have found a bug in the code. I noticed that searches that are enclosed in quotes, such as "hello there" alway return 0 results. The problem is the “$input = htmlspecialchars($input);” line in the cleanSearch function. It’s screwing up the quotes so that Google doesn’t recognize them. I commented out that line and it fixed the problem. I don’t notice any negative effects of removing that line, but if you’re aware of some then it might be worthwhile to rewrite that portion so that quotation marks are left alone.

    Thanks again,
    Bryan

  11. Artas on January 17th, 2008 4:36 am

    Very relevant discussion. We would also like to run your script on our website, but it is, unfortunately, written in PHP4.

    So i was thinking - Bryan do you plan on sharing your modified script with the uneducated masses like me?

    Your goodwill would be much appreciated.

    Thanks
    Artas

  12. oyunlar on January 30th, 2008 12:21 am

    thanks

  13. Video Hugger on February 8th, 2008 8:04 am

    Thanks for the script!

  14. mahdi on February 11th, 2008 2:43 am

    hi
    can you design i for php 4?
    can i use this with free version of custom search?

    i want to use it here:
    http://www.rapid2share.com

    tnx for your good app

  15. Sean on May 19th, 2008 3:38 pm

    Worked perfectly. Thanks!

  16. sozluk on June 14th, 2008 2:00 pm

    its very useful. thanks

  17. Hemant Goyal on June 22nd, 2008 1:50 am

    Hello Friend,
    I am Geeting a Warning (Warning: Invalid argument supplied for foreach() in C:\Domain\sufiyacollege.com\wwwroot\google\ on Line 80. Plz Tell me How i Can Fix This Problem. and Also my Search Geeting “There are No Result” Error.
    Thank you.

  18. Jatin Arora on July 28th, 2008 6:53 am

    hi i want to tell me about the tax. tax all type of tax sale tax income tax

  19. Jatin Arora on July 28th, 2008 6:56 am

    You should definitely see if you host plans to upgrade their php, and try to get them to if they aren’t planning it. PHP4 is past its End of Life as php6 is just around the corner. They may also have servers with php5 on them that they can transfer your domain to with little difficulty.

    As far as using it with php4, I would look around for a php4 class that mimics the simpleXML class. If I come across one that looks decent, I’ll post it up here.

Got something to say?