**UPDATED** Adding Google Business search to your ecommerce website

November 26, 2008

**UPDATED**
This is an updated version of the script. It now resides on only a single page and should be less confusing to put into a website. Please feel free to use this script as a base and customize as you like.

Sign up for a business site search account here: http://www.google.com/sitesearch/index.html

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. Upload this to your website, enter your account id, and make a form to post to it. 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 name is "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 site-search.php or something similar. Edit the $accountId variable with your specific google search information.

PHP:
  1. <?php
  2. /*
  3. AUTHOR: Jamie Estep
  4. WEBSITE: http://www.ecommerce-blog.org
  5. LICENSE:
  6. This program is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 3 of the License, or
  9. (at your option) any later version.
  10. This program is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13. GNU General Public License for more details.
  14. For a copy of the GNU General Public License see
  15. <http://www.gnu.org/licenses/>
  16. */
  17.  
  18. function cleanSearch($input){
  19.     //this will clean the query so that it is safe to use for whatever
  20.     //this is broken into steps, but can be done on a single line if prefered
  21.    
  22.     //trim whitespace
  23.     $input = trim($input);
  24.    
  25.     //if you would like your users to be able to search for code, you can comment this out
  26.     //Make sure you know what you're doing before you comment this out!
  27.     $input = strip_tags($input);
  28.    
  29.     //Convert html characters to a safe format, IE: & - &amp; etc.
  30.     $input = htmlspecialchars($input);
  31.    
  32.     //convert to a url safe code since we use the GET function to request from google
  33.     $input = urlencode($input);
  34.    
  35.     return $input;
  36. }
  37.  
  38. function replaceChars($input){
  39. //using this function to replace some html from the data returned by google
  40. //Make sure there is a corresponding value in the find and replace arrays or you will have problems
  41.    
  42.     //these are what you want to replace
  43.     $find = array(
  44.     '»',
  45.     '<br>'
  46.     );
  47.    
  48.     //these are what you need to replace them with
  49.     $replace = array(
  50.     '&raquo;',
  51.     ''
  52.     );
  53.    
  54.     return str_replace($find,$replace,$input);
  55.  
  56. }
  57.  
  58. //constants
  59. $accountId   = '';             //put google search ID Here - Should be a long string of numbers letters and symbols
  60. $collation      = 'ISO-8859-1';     //change this if you want something other than ISO-8859-1, IE: ut8-f
  61. $numberPerPage  = '10';    //this is how many results you want per page
  62. $noResults   = 'There were no results found for your search. Please try again.'; //Message if no results are found
  63. ?>
  64.  
  65.  
  66. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  67. <html xmlns="http://www.w3.org/1999/xhtml">
  68. <head>
  69. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  70. <title>My Custom Search</title>
  71. </head>
  72.  
  73. <body>
  74.  
  75. <!-- Start Search Box -->
  76. <table width="100%" border="0" cellspacing="0" cellpadding="10">
  77.   <tr>
  78.     <td align="center" valign="middle">
  79.    
  80.     <form action="<?php echo $_SERVER['PHP_SELF'];?>">
  81.         <input name="query" type="text" size="40" value="<?php if($_GET['query']): echo urldecode(cleanSearch($_GET['query'])); endif; ?>" />
  82.         <input type="submit" name="sa" value="Search" />
  83.         <img src="http://google.com/coop/images/google_custom_search_smnar.gif" alt="Google Custom Search" />
  84.    </form>
  85.    
  86.     </td>
  87.   </tr>
  88. </table>
  89. <!-- End Search Box -->
  90.  
  91. <?php
  92.  
  93. //check if the form was submitted
  94. if(!empty($_GET['query'])):
  95.    
  96.     //clean the input so that it is safe
  97.     $searchTerm = cleanSearch($_GET['query']);
  98.    
  99.     //cast $_GET['start'] to an integer just in case
  100.     $start = (int)$_GET['start'];
  101.    
  102.     //build the google query here
  103.     $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;
  104.    
  105.     //get the result for the query from google
  106.     $thisSearch = file_get_contents($buildQuery);
  107.    
  108.     //instantiate a simple xml class and process the google result
  109.     $xml = new SimpleXMLElement($thisSearch);
  110.    
  111.     //find the number of results for pagination later on
  112.     $total = ;
  113.    
  114.     //Display Nothing found message if there are no results.
  115.     if($total <1): ?>
  116.    
  117.         <p><?php echo $noResults ; ?></p>
  118.    
  119.     <?php
  120.     else:
  121.        
  122.         //loop through the results
  123.         foreach ($xml->RES->R as $key):
  124.            
  125.             //the replaceChars removes anything you need it to, I found google returning some unusable characters, and you can fix it with this function
  126.             //Edit the actual find / replace at the bottom
  127.            
  128.             //format the output for each result
  129.            
  130.             ?>
  131.            
  132.             <p><a href="<?php echo $key->U; ?>"><?php echo replaceChars($key->T); ?></a><br />
  133.             <?php echo replaceChars($key->S); ?><br />
  134.             <span style="color:#060;"><?php echo $key->U; ?></span></p>
  135.  
  136.         <?php
  137.         endforeach;
  138.        
  139.         //simple pagination ?>
  140.         <table width="100%" border="0" cellspacing="0" cellpadding="5">
  141.             <tr>
  142.        
  143.         <?php
  144.             //make sure we dont display previous page on the first page
  145.             if ($start> 0): ?>
  146.            
  147.                 <td align="left"><a href="?query=<?php echo $searchTerm; ?>.'&start=<?php echo ($start - $numberPerPage); ?>">&laquo; Previous 10</a></td>
  148.            
  149.             <?php endif;
  150.            
  151.             //make sure we dont display next page on the last page
  152.             if ($total == $numberPerPage): ?>
  153.                
  154.                 <td align="right"><a href="?query=<?php echo $searchTerm; ?>&start=<?php echo ($start + $numberPerPage); ?>">Next 10 &raquo;</a></td>
  155.                    
  156.             <?php endif; ?>
  157.        
  158.             </tr>
  159.         </table>
  160.         <?php /*
  161.         I ALWAYS APPRECIATE CREDIT FOR WORK THAT I HAVE DONE,
  162.         BUT FEEL FREE TO REMOVE THIS LINK.
  163.         REMOVAL OF THIS LINK DOES NOT VALIDE LICENSE AGREEMENT!
  164.         THANKS */
  165.         ?>
  166.         <p align="center">Google search script provided by <a href="http://www.ecommerce-blog.org/" target="_blank">an Ecommerce Blog</a>.</p>
  167.     <?php
  168.     endif;
  169. endif;
  170.  
  171. ?>
  172.  
  173. </body>
  174. </html>

Example of how to implement it:

Download this file along with it's license. http://www.ecommerce-blog.org/site-search.zip

Enter your site's google custom search account id, and upload the file to your server. You can also post a search directly to the site-search.php page using a GET request.

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

25 Responses to “**UPDATED** 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.

  20. Giannis on October 19th, 2008 7:08 pm

    Hello. I am also getting this error…

    Warning: Invalid argument supplied for foreach() in /home/chill/public_html/g3/googleSearch.php on line 78

    How can this be fixed?? Thank you in advance

  21. vkpal on November 20th, 2008 2:27 pm

    hey
    plz remove this error
    Warning: Invalid argument supplied for foreach() in /home/chill/public_html/g3/googleSearch.php on line 78

  22. jestep on November 24th, 2008 10:22 pm

    Not sure what’s causing that. I’ll take a look at it and update the script this week. It’s most likely that no search results were returned, and there isn’t really any error control. Check back on tomorrow for an updated script.

  23. pavan on November 25th, 2008 11:17 pm

    hiiya,
    i’m getting these warnings when i queried for a search.

    Warning: file_get_contents(http://www.google.com/search?cx=&client=google-csbe&start=0&num=10&output=xml_no_dtd&q=google&ie=ISO-8859-1&oe=ISO-8859-1) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden in C:\wamp\www\googleSearch\googleSearch.php on line 62

    Fatal error: Uncaught exception ‘Exception’ with message ‘String could not be parsed as XML’ in C:\wamp\www\googleSearch\googleSearch.php:65 Stack trace: #0 C:\wamp\www\googleSearch\googleSearch.php(65): SimpleXMLElement->__construct(”) #1 C:\wamp\www\googleSearch\site-search.php(9): include(’C:\wamp\www\goo…’) #2 {main} thrown in C:\wamp\www\googleSearch\googleSearch.php on line 65

    i dont know what the accountID is in the search.php.
    please let me know the accountID.
    many thanks,
    pavan.p

  24. jestep on November 26th, 2008 3:23 pm

    The account id is what google gives you when you sign up for a business search account.

    Go to: http://www.google.com/sitesearch/index.html to sign up for an account.

  25. direct debit payment on December 5th, 2008 5:11 pm

    sounds like it could be worthwhile. thanks for the headsup.
    -jack

Got something to say?