**UPDATED** Adding Google Business search to your ecommerce website
**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.
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 /* AUTHOR: Jamie Estep WEBSITE: http://www.ecommerce-blog.org LICENSE: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. For a copy of the GNU General Public License see <http://www.gnu.org/licenses/> */ function cleanSearch($input){ //this will clean the query so that it is safe to use for whatever //this is broken into steps, but can be done on a single line if prefered //trim whitespace $input = trim($input); //if you would like your users to be able to search for code, you can comment this out //Make sure you know what you're doing before you comment this out! $input = strip_tags($input); //Convert html characters to a safe format, IE: & - & etc. $input = htmlspecialchars($input); //convert to a url safe code since we use the GET function to request from google $input = urlencode($input); return $input; } function replaceChars($input){ //using this function to replace some html from the data returned by google //Make sure there is a corresponding value in the find and replace arrays or you will have problems //these are what you want to replace $find = array( '»', '<br>' ); //these are what you need to replace them with $replace = array( '»', '' ); return str_replace($find,$replace,$input); } //constants $accountId = ''; //put google search ID Here - Should be a long string of numbers letters and symbols $collation = 'ISO-8859-1'; //change this if you want something other than ISO-8859-1, IE: ut8-f $numberPerPage = '10'; //this is how many results you want per page $noResults = 'There were no results found for your search. Please try again.'; //Message if no results are found ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>My Custom Search</title> </head> <body> <!-- Start Search Box --> <table width="100%" border="0" cellspacing="0" cellpadding="10"> <tr> <td align="center" valign="middle"> <form action="<?php echo $_SERVER['PHP_SELF'];?>"> <input name="query" type="text" size="40" value="<?php if($_GET['query']): echo urldecode(cleanSearch($_GET['query'])); endif; ?>" /> <input type="submit" name="sa" value="Search" /> <img src="http://google.com/coop/images/google_custom_search_smnar.gif" alt="Google Custom Search" /> </form> </td> </tr> </table> <!-- End Search Box --> <?php //check if the form was submitted if(!empty($_GET['query'])): //clean the input so that it is safe $searchTerm = cleanSearch($_GET['query']); //cast $_GET['start'] to an integer just in case $start = (int)$_GET['start']; //build the google query here $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; //get the result for the query from google $thisSearch = file_get_contents($buildQuery); //instantiate a simple xml class and process the google result $xml = new SimpleXMLElement($thisSearch); //find the number of results for pagination later on $total = ; //Display Nothing found message if there are no results. if($total < 1): ?> <p><?php echo $noResults ; ?></p> <?php else: //loop through the results foreach ($xml->RES->R as $key): //the replaceChars removes anything you need it to, I found google returning some unusable characters, and you can fix it with this function //Edit the actual find / replace at the bottom //format the output for each result ?> <p><a href="<?php echo $key->U; ?>"><?php echo replaceChars($key->T); ?></a><br /> <?php echo replaceChars($key->S); ?><br /> <span style="color:#060;"><?php echo $key->U; ?></span></p> <?php endforeach; //simple pagination ?> <table width="100%" border="0" cellspacing="0" cellpadding="5"> <tr> <?php //make sure we dont display previous page on the first page if ($start > 0): ?> <td align="left"><a href="?query=<?php echo $searchTerm; ?>.'&start=<?php echo ($start - $numberPerPage); ?>">« Previous 10</a></td> <?php endif; //make sure we dont display next page on the last page if ($total == $numberPerPage): ?> <td align="right"><a href="?query=<?php echo $searchTerm; ?>&start=<?php echo ($start + $numberPerPage); ?>">Next 10 »</a></td> <?php endif; ?> </tr> </table> <?php /* I ALWAYS APPRECIATE CREDIT FOR WORK THAT I HAVE DONE, BUT FEEL FREE TO REMOVE THIS LINK. REMOVAL OF THIS LINK DOES NOT VALIDE LICENSE AGREEMENT! THANKS */ ?> <p align="center">Google search script provided by <a href="http://www.ecommerce-blog.org/" target="_blank">an Ecommerce Blog</a>.</p> <?php endif; endif; ?> </body> </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.
Subscribe to the RSS feed and have all new posts delivered straight to you.
[…] 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/ […]
[…] Ecommerce Blog has written a script to help you add the new custom Google business search to your […]
[…] eCommerce Blog has posted a simple script to help you add a Google business search engine to your own […]
Updated the script to add support for no results found. Sep 19, 2007
Do you have a example ?
I’m using this script on my main business website here:
http://www.merchantequip.com/
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
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.
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
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
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.
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
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
thanks
Thanks for the script!
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
[…] 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 […]
Worked perfectly. Thanks!
its very useful. thanks
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.
hi i want to tell me about the tax. tax all type of tax sale tax income tax
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.
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
hey
plz remove this error
Warning: Invalid argument supplied for foreach() in /home/chill/public_html/g3/googleSearch.php on line 78
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.
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
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.
sounds like it could be worthwhile. thanks for the headsup.
-jack
I think it is better to use PHP tHAN ajax…
Thanks for the script. I have been trying to implement this for a client.
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.
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
nothing happens..
always no search results..
even google image is not displayed..
This is really fantastic so that we can get more help to add a Google business search engine..keep it up..chears
Wow! Thanks for this!!!
thank you sir very nice text
add a Google business search engine..keep it up..chears
Thanks for information, this e-commerce script works fine for lot of users, however there are some bugs if you are first time runner.
That’s a handy little script. I’m going to save it and implement it. Thank you!
cool, gonna try 🙂
Not working. Lots of errors.
This is really cool and i am going to try it right away.
Will update later
Thanks for Sharing costume search code which we could implement on our site and easily can get use that with ant problem
Perfect really useful just what I was looking for!
Useful post! not just for website SEO but also for the programmers also to implement it with ease.
I have been trying to implement this for a client. Thank You!