SayNoToFlash

PHP, Symfony, Web Development

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

June 29th, 2009 in: PHP, Scripts

**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.

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.

(Add your own) Comments

  • jestep 9:52 am on September 18th, 2007

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

  • toto 7:56 am on September 19th, 2007

    Do you have a example ?

  • jestep 7:59 am on September 19th, 2007

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

  • joerge 11:08 pm on October 2nd, 2007

    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

  • jestep 9:00 am on October 3rd, 2007

    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.

  • Jest Staffel 8:54 am on October 14th, 2007

    there is also a large and comprehensive database of 500 ajax scripts available with over at ajaxflakes’s ajax scripts compound

    thought i should add it might be helpful to others…

    http://scripts.ajaxflakes.com

  • Bryan 7:01 pm on November 20th, 2007

    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

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

    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.

  • Bryan 3:02 pm on November 29th, 2007

    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

  • Artas 4:36 am on January 17th, 2008

    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

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

    thanks

  • Video Hugger 8:04 am on February 8th, 2008

    Thanks for the script!

  • mahdi 2:43 am on February 11th, 2008

    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

  • Sean 3:38 pm on May 19th, 2008

    Worked perfectly. Thanks!

  • sozluk 2:00 pm on June 14th, 2008

    its very useful. thanks

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

    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.

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

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

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

    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.

  • Giannis 7:08 pm on October 19th, 2008

    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

  • vkpal 2:27 pm on November 20th, 2008

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

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

    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.

  • pavan 11:17 pm on November 25th, 2008

    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

  • jestep 3:23 pm on November 26th, 2008

    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.

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

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

  • JMM 3:11 am on March 25th, 2009

    I think it is better to use PHP tHAN ajax…

  • Enrique 10:43 pm on April 17th, 2009

    Thanks for the script. I have been trying to implement this for a client.

  • oyunlar 11:19 am on May 8th, 2009

    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.

  • yarisma 11:19 am on May 8th, 2009

    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

  • vinit 1:04 pm on May 27th, 2009

    nothing happens..

    always no search results..

    even google image is not displayed..

  • bryan williamz 1:05 am on June 8th, 2009

    This is really fantastic so that we can get more help to add a Google business search engine..keep it up..chears

  • Rob Abdul 7:27 am on June 13th, 2009

    Wow! Thanks for this!!!

Trackbacks

  • ProphetsLodge Presents &r&hellip on December 31st, 2006 at 2:29 pm

    [...] I think I’ll write a more detailed post in the future on this as it’s quite a big topic, and I was more focused on the functionality that is available at the minute from some of the frameworks, but the main theme that I have picked up on during my research is that is isn’t the be all and end all that a lot of folk are claiming it to be. Between us I think we acknowledge this fact and we will need to use the technology where it is most appropriate on future sites that we are involved in. On this theme I found this article quite interesting. Onto AJAX frameworks then, we’ve probably got a list of bookmarks with several frameworks noted, if not check out this listing http://www.ajaxmatters.com/blog/ajax-frameworks/ [...]

  • Pilgrim’s Picks for&hellip on July 20th, 2007 at 8:59 am

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

  • Getting into Google Custo&hellip on July 20th, 2007 at 1:59 pm

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

  • AJAX Technology and eComm&hellip on March 18th, 2008 at 8:37 pm

    [...] it depends on how you implement ECF into your overall strategy, but if used smartly, AJAX can benefit the customer experience in various ways, including dynamic shopping carts, shipping calculators, and product descriptions without having to [...]

 
   Leave a Comment   
Required
Required

Comment Policy - Do Not Post:

  1. Spam!
  2. Blatant self-promotion!
  3. Any email address or phone number!

Comments that do not meet these guidelines will not be visible on this website. All comments are moderated before they are visible on this website.

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed

Copyright © 2009 SayNoToFlash · theme design by Jamie Estep · Log in