PHP Tip: Add Custom Google Search Results to Your Site with PHP
Friday, January 16th, 2009
Have you ever wanted to integrate a custom google search on your site, and style it to your liking? Today, one of our new Dev-Tips author Brian Cray will take you through adding custom google search results to your site with php.
What you need
Quickly...
- Mike Migurski's PHP JSON decoder
allow_url_fopenset toOnin your PHP.INI (many hosts have this on by default)- A desire to learn to be even more awesome than you already are
You'll end up with 2 files to make things work: search.php that shows a search form and results and querygoogle.php that pulls search results from Google. Put the CSS used in this tutorial wherever you want... if you want it.
How will this make your life better?
Being the awesome Web developer/designer/jack-of-all-tradeser you are and your clients know you are, you receive frequent requests to add a "little search box" as a part of your client's Web site. What follows is a twitch you disguise as a sneeze because you know you haven't got a solid easy-to-impliment custom solution that the client won't groan at.
But that'll all change now. Armed with a little PHP wizardry, we can turn you into a star. This is a ridiculously easy to implement solution for adding CSS-able custom results straight from Google to your client's Web site. And, we'll do it all in 3+1 easy steps. (note: please read Google's Terms of Use).
Step 1: The search form/page - search.php
Since computers can't yet read minds, we'll have to create a simple search form that includes a text field for the search query and a search button. This should be pretty ho-hum to you, but it's important nonetheless.
Notice the form posts to querygoogle.php. We'll create that script in step 2.
<form method="post" action="querygoogle.php"> <label for="searchquery"><span class="caption">Search this site</span> <input type="text" size="20" maxlength="255" title="Enter your keywords and click the search button" name="searchquery" /></label> <input type="submit" value="Search" /> </form>
Yeah baby! We've created a simple search form ready for any daunting search challenge. Let's create the real muscle be your custom search engine, the famed querygoogle.php.
Step 2: The script to query Google - querygoogle.php
Now the fun stuff you've been skip scrolling to see (I know your scanning tendancies!). I wrote this PHP script to take advantage of Google's AJAX Search API to provide a transparent, usable, branded experience to end-users. My customers were happy, and yours will be too. Save this PHP as querygoogle.php.
Here's what the code is doing:
- Includes the JSON library
- Sets up the URL that you will give you Google's search results. The URL includes your domain to make it a site specific search and the user's search query. The search uses Google's "site:domain.com keywords" search syntax
- Uses fopen and fread to grab the JSON that results from a call to Google
- Decodes the JSON into a PHP object with Mike's JSON library
- Iterates through the object, creating custom HTML-formatted results
- Sets a session variable that contains the custom HTML-formatted results to send to your custom results page
- Uses PHP's header function to send the browser to your custom results page
<?php
session_start();
// if you use an Mike Migurski's JSON library, include it like I did
require_once('JSON.phps');
// Here's the Google AJAX Search API url for curl. It uses Google Search's site:www.yourdomain.com syntax to search in a specific site. I used $_SERVER['HTTP_HOST'] to find my domain automatically. Change $_POST['searchquery'] to your posted search query
$url = 'http://ajax.googleapis.com/ajax/services/search/web?rsz=large&v=1.0&q=' . urlencode('site:' . $_SERVER['HTTP_HOST'] . ' ' . $_POST['searchquery']);
// use fopen and fread to pull Google's search results
$handle = fopen($url, 'rb');
$body = '';
while (!feof($handle)) {
$body .= fread($handle, 8192);
}
fclose($handle);
// now $body is the JSON encoded results. We need to decode them.
$json = new Services_JSON();
$json = $json->decode($body);
// now $json is an object of Google's search results and we need to iterate through it.
foreach($json->responseData->results as $searchresult)
{
if($searchresult->GsearchResultClass == 'GwebSearch')
{
$formattedresults .= '
<div class="searchresult">
<h3><a href="' . $searchresult->unescapedUrl . '">' . $searchresult->titleNoFormatting . '</a></h3>
<p class="resultdesc">' . $searchresult->content . '</p>
<p class="resulturl">' . $searchresult->visibleUrl . '</p>
</div>';
}
}
$_SESSION['googleresults'] = $formattedresults;
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;
?>
Important Note
We are having a small issue with the code syntax formatting, be sure the '&' signs in the url on line 9 above do *not* have a semicolon after them. Please see 'Renes' comment below for more. Apologies for the inconvenience!
Step 3: The results page - back to search.php
I know you're itching to see the results. So was I! Boy I wish I could do it all over again for the first time...
Anyway, the HTML formatted results are now stored in a PHP session variable from querygoogle.php. Groovy. All we have to do is display them and add some more CSS to make the results look sexy.
Make sure you can pull the results from the session by verifying that you are starting the session at the beginning of search.php and then echo the results. See below for the final search.php code (we started it in Step 1):
<?php
session_start();
?>
<form method="post" action="querygoogle.php">
<label for="searchquery"><span class="caption">Search this site</span> <input type="text" size="20" maxlength="255" title="Enter your keywords and click the search button" name="searchquery" /></label> <input type="submit" value="Search" />
</form>
<?php
if(!empty($_SESSION['googleresults']))
{
echo $_SESSION['googleresults'];
unset($_SESSION['googleresults']);
}
?>
Your search results work! But they're ugly. Here's some sexy CSS like I promised to get your started.
body
{
background-color: #000;
color: #ccc;
font: .75em/1.5em Arial, sans-serif; /* EMs calculated with pxtoem.com */
padding: 1.5em;
margin: 0;
width: 40em;
}
.searchresult
{
padding: 1.5em 0;
border-bottom: 1px solid #333;
}
.searchresult h3, .searchresult p
{
margin: 0;
}
.searchresult h3 a
{
font: italic 1em Georgia, serif;
color: #f30;
border-bottom: 1px solid #900;
text-decoration: none;
font-weight: bold;
font-size: 1em;
}
.searchresult .resultdesc b
{
color: #fff;
}
.searchresult .resulturl
{
color: #666;
font-size: .75em;
}
If you'd like to style your own results your way, each result will be placed in the following HTML format:
<div class="searchresult"> <h3><a href="page-url">Page Title</a></h3> <p class="resultdesc">Page description/highlights</p> <p class="resulturl">URL that google always shows in green</p> </div>
Step 3+1: Celebrate!
Congratulations! Your clients are happy. You've worked hard and you should take some "you time."
Need Web Hosting?
If you're looking for a quality web host, check out Web Hosting Search for an array of quality hosting services.
If you enjoyed this article, you might consider subscribing to our rss feed to stay updated with all the latest tips and articles!
Article Sponsored by:
Quench is a premium XHTML and php based theme developed by Drew Douglass of Dev-Tips. Quench is packed full of features and is perfect for a portfolio, blog, or personal web site. It also includes a working contact form and integrates your twitter status on the homepage.
68 Comments
subscribe comments feedTrackbacks/Pingbacks
- AndySowards.com :: Web Development Nerdy Daily Links For 1/20/2009 | AndySowards.com :: Professional Web Design, Development, Programming, Hacks, Downloads, Math and being a Web 2.0 Hipster?
- 20 Useful PHP Components & Tutorials for Everyday Project | Noupe
- links for 2009-03-03 « Richard@Home
- Angels Picks » Blog Archive » 20 Useful PHP Components & Tutorials for Everyday Project
- Brian Cray.com is redesigned / Brian Cray's Blog
- 20 Useful PHP Components & Tutorials for Everyday Project | YABIBO.COM - YOUR WEB WORLD
- [Php Tutorial] Add Custom Google Search Results to Your Site with PHP | Beyond Venture Design









Good stuff – I would revisit line 19 in the Step 2 code listing if I was you, however.
nice..thnx
Good call Dean! Problem resolved! Thanks so much for your feedback!
Am getting this service error
Fatal error: Class ‘Services_JSON’ not found in D:\xampp\htdocs\harusi\querygoogle.php on line 22
Great post Brian! finally I can stop using obsolete Google search SOAP. Thanks.
Glad you liked it! Thanks!
Great detailed steps Brian.
If I have a secure site that requires user login and I do not want to make the site content public at all, can I still use Google search ? i.e. only users that login can search and the search results nor site content are publicly available. Only to logged in users.
@John L.,
Thanks John. I’m sad to say that unfortunately this only works if Google is indexing your pages.
I can’t seem to get it to work. I get a warning…
“Warning: Invalid argument supplied for foreach() in /home/irishtit/public_html/09/querygoogle.php on line 29″
If I echo the $body variable in querygoogle.php it says:
{“responseData”: null, “responseDetails”: “invalid version”, “responseStatus”: 400}
Did you try it more than once? Did you verify the domain name that you are searching and that it has results in Google?
Hey Brain,
I tried it again and it doesn’t work.
Here is my site
Use the search box and you can see the results yourself.
Thanks,
Tegan
Hi Brian,
I got the same warning as Tegan. I tried it both in PHP 4 and PHP 5 enviroment.
allow_url_fopen is set to On in PHP.INI
Google site:domain.com queary works.
Any suggestions?
Found a solution: You got to remove all these amp; Tags from $url at line 9 ! Just use the “&” instead.
This works:
$url = 'http://ajax.googleapis.com/ajax/services/search/web?rsz=large&v=1.0&q=' . urlencode('site:' . $_SERVER['HTTP_HOST'] . ' ' . $_POST['searchquery']);Thank you Rene, we are having a slight issue with the code formatting but I have edited it and made a note below the code to inform everyone. Thanks!
Thank you very much Rene. I appreciate it very much!
Thank you for writing this tutorial. I recently implemented Google’s CSBE for a client and it was a big hassle. Your method seems a lot more straightforward, however a couple of things aren’t clear to me, perhaps because I am a PHP noob, and I apparently haven’t put this together right.
If you would post a link to one of the sites you’ve done that includes this script it would be most helpful.
WIll take a look at it… perhaps Google changed something… look for update soon!
Thanks Brain! I will look forward to your update.
Any thoughts on pagination?
BTW, for all who need their country-specific characters to be displayed (ISO 8859-1), just replace
$_SESSION['googleresults'] = $formattedresults;with
$_SESSION['googleresults'] = utf8_decode($formattedresults);I removed all the extraneous ampersands – thanks for the tip, Rene.
I’m finding it confusing that the first step is labeled search.php but seems to contain the form code, which doesn’t seem like it should be in the search.php script. Then after the discussion about the querygoogle script we go back to search.php and insert session_start();, etc., before the form code and echo $_SESSION['googleresults'];, etc. after the form code???
I think it would be helpful if someone were to just post what working code should look like in the search.php file.
pagination?
Has anybody got this to work yet? Can somebody package this up in a zip? I’m still getting errors… shucks
If you’re using PHP5, you may not need the JSON class. PHP5 includes two functions,
json_encode()andjson_decode()that might be able to do the trick for you without the include. Just be aware of the second parameter to json_decode(); if that paramter is true, the function returns a PHP array but if it’s false you get astdClassobject, if I remember correctly. Usually, I’m shooting for an array.@David true… I wanted to make this function work for people running PHP 4, too. Your solution is definitely worth looking into if PHP is installed.
I had a few of the same problems as listed above. One thing I noticed is that if you right click the link for the JSON decoder and select “save as”, the contents of the file is not the same as if you were to click the link to view the file in your browser and copy/paste the contents of JSON.phps to a new file (or save that page).
Fortunately, this solved my problems. I agree that it would be nice to have a link to the complete source files. Thanks for this great tutorial!!
Thank’s for this tutorial.
Why is there only 4 results?
…never mind. I was using this tutorial in conjuction with the google documentation [http://code.google.com/apis/ajaxsearch/documentation/#fonje_snippets_php] (because I’m using PHP5 and don’t want to bother with that JSON decoder library) and didn’t use the correct url.
But since i’m on the subject, do you know how we get to the rest of the results…pagination?
This has been a huge help, thanks!
Maybe this is a n00b question, but why do you need to use the unset(). What is the worst-case scenario for non-critical data. The problem I see with unset() for this case is that it breaks the back button for anyone doing a search on your site. If you unset it there, when they click a result and then click back in their browser they come back to a blank page. When they do a new search it will overwrite the old session data, so the only bad I see is a session file temporarily on the server that is bigger than 0kb. The Google Search API limits to such a small result set that even with the maximum 32 results, the session file will never be that big, and is only temporary, right?
As an aside, when I used this code, I moved the form to a header include file for my site, that way the search form is at the top of all of the pages. Then the search.php page is just a results page. So the form sends the ’searchquery’ text post to the querygoogle.php but on the querygoogle.php file I changed the Location redirect to the search.php (rather than back to the HTTP_REFERER which for me could be any page on the site).
Thanks again for writing this up. I am brand new to the search api, and know next-to-nothing about sessions so the fact that I got it even working at all is a testament to a good tutorial.
nice work, but didn’t work on me.
i did exactly how you explained. but when i try to search smt it tries to open the codes.
you must test it urself:
http://www.genstr.com/test/
Nice tutorial. However, I was wondering what are the benefits of this script over Google’s Custom Search Engine?
awesome! gave some great ideas for incorporating google into my website
Hi. Very long time I´m looking for some customize of google for google results. What I meen is: When you look for some word in google, and google returned the results, they are 1 row for the title, 2 row for the text, and 1 row for the link. I want to change the 2 rows for the text, and make them 6,7 or 8 rows. It´s possible?
This is great, but I am wondering if its ok with google terms of service. I would like to take results from google movie search and put on my site, showtimes and theaters etc. If i grab the data and parse it into my site, does anyone know if its allowed?
If you take a look at the terms of use as Brian stated you can probably find your answer
http://code.google.com/apis/ajaxsearch/terms.html
cool update mann
ill enjoy it.
Use of the Services by you
5.3 You agree not to access (or attempt to access) any of the Services by any means other than through the interface that is provided by Google, unless you have been specifically allowed to do so in a separate agreement with Google. You specifically agree not to access (or attempt to access) any of the Services through any automated means (including use of scripts or web crawlers) and shall ensure that you comply with the instructions set out in any robots.txt file present on the Services.
5.5 Unless you have been specifically permitted to do so in a separate agreement with Google, you agree that you will not reproduce, duplicate, copy, sell, trade or resell the Services for any purpose.
——-
So we are not allowed to access the info other than through the interface and also not allowed to reproduce (display) the info once we have accessed it.
Thats not good.
I’ve seen sites/apps accessing and reproducing google info, so I guess they don’t enforce strictly?
Hi..
Can you please tell me that, still this functionality providing by google as free. I would like to use it for my webste…
So, I cant get this to work.
I created both pages and when I search a keyword, it goes to querygoogle.php, then the pages goes blank. It does not return me to the search.php page. Nor does it display any kind of search results.
Any ideas?
So I got it to work, there were some issues in the JSON.phps.
Anyway, it works, all but 2 important things seem to be missing.
1- It only displays 8 results.
2- There is no pagination.
Anyone have any tips for these 2 issues?
I am also facing the same problem:
1. only 8 results are there
2. How to get the next results. I want to have at least 20 to 50 results. This can be in two iterations but I need to get at least 20 results.
Please help ASAP.
This is a great pics of work. I may use it on my site. Love it. Thank you.
i m behind proxy so i use curl to read the url and feed the output to json_decode it gives me Invalid argument “foreach()”::
Can u exapin why??
$json = json_decode($body);
foreach($json->responseData->results as $searchresult)
//Warning: Invalid argument supplied for foreach()
I am also facing the same problem as discussed above but didn’t get the solution.
Invalid argument supplied for foreach()
foreach($json->responseData->results as $searchresult)
when I check it from myself responseData and result were absent in the JSON.phps.
Can I use google custom search in my local machine.
Please help I am really needy at this time.
thanks
Rajat Singh
This is the main problem when I tried to print json object I got this type of information which shows the version is invalid
response 400.
[responseData] =>
[responseDetails] => invalid version
[responseStatus] => 400
Please help me to find the suitable solution.
thanks
Rajat Singh
is it possible to integrate the above functionality on locahost
pls help me
I’m new to php and can’t get this to work. It says:
decode($body); // now $json is an object of Google’s search results and we need to iterate through it. foreach($json->responseData->results as $searchresult) { if($searchresult->GsearchResultClass == ‘GwebSearch’) { $formattedresults .= ‘
‘ . $searchresult->titleNoFormatting . ‘
‘ . $searchresult->content . ‘
‘ . $searchresult->visibleUrl . ‘
‘; } } $_SESSION['googleresults'] = $formattedresults; header(‘Location: ../results.html’ . $_SERVER['HTTP_REFERER']); exit; ?>
any ideas?
thanks,
jake
Мы подготовили современный журнал про новый сериал маргоша. Только здесь можно скачать онлайн молодежный сериал маргоша. Представляем Вам актуальные новости про сериал маргоша. Для Вас красочные фотографии из сериала маргоша.
Hi i tried this code but i am not getting any response data in that session array can you please tell me is it related to some apache settings,i checked my allow_url_fopen it is on too.
I live is connected to the city by local trains. ,
U can use simple pagination by returning results via ajax api.
just add the starting point of the search result in the link.
example :
$url = ‘http://ajax.googleapis.com/ajax/services/search/web?rsz=large&v=1.0&start=8&q=’denis’;
with start=8 we get results for the page 2, with start=16 page 3 and so on until start=56, because ajax api returns max 64 results.
This is only for 8 result per page. If u have less do the math yourself.
Great post,
but would like to emphasize that in querygoogle.php at line9: “$_SERVER['HTTP_HOST']” .It shoul be $_SERVER['HTTP_POST']
Thanks a lot, It really helped me to solve the program problem.
Is there a way to customize this script t. search Google.co.uk (pages from uk)
Am getting this error.
Fatal error: Class ‘Services_JSON’ not found in D:\xampp\htdocs\harusi\querygoogle.php on line 21
i think in the example above only applies to web search,
how to search for other types such as VideoSearch, Blogsearch, NewsSearch, ImageSearch, BookSearch, PatentSearch?
Can this script be used to search web instead of only one site. How does the code change with that. Is it possible to put in a hidden query also?
nice infos…thanks.
Nice Post.. it was helped lot..
thanks
Brain
Hi,
can anyone please specify why do I always get after submiting a PHP code of the querygoogle.php file ?
I will be very thankfull for any response
My search results in only one result. How do I set the expand_mode_open to turn on.
Please help.