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_fopen set to On in 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:

  1. Includes the JSON library
  2. 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
  3. Uses fopen and fread to grab the JSON that results from a call to Google
  4. Decodes the JSON into a PHP object with Mike's JSON library
  5. Iterates through the object, creating custom HTML-formatted results
  6. Sets a session variable that contains the custom HTML-formatted results to send to your custom results page
  7. 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):

&lt;?php
session_start();
?&gt;

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

&lt;?php
if(!empty($_SESSION['googleresults']))
{
echo $_SESSION['googleresults'];
unset($_SESSION['googleresults']);
}
?&gt;

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!

ABOUT THIS AUTHOR

Brian Cray is a marketing & Internet strategy consultant, web developer, and Apple fanatic living in Columbus, Ohio, USA. His work has been featured by Mashable, NETTUTS, Smashing Magazine, and many others. He's happy to share his knowledge with you on DevTips and his own blog at Brian Cray.com.
  1. January 17, 2009 at 9:33 am
    • sm
      September 27, 2009 at 8:56 pm
  2. January 18, 2009 at 11:32 am
    • October 22, 2009 at 4:55 am
  3. January 29, 2009 at 3:58 pm
  4. Jonn L.
    March 2, 2009 at 8:13 am
  5. March 2, 2009 at 8:16 am
  6. March 2, 2009 at 9:05 am
  7. March 2, 2009 at 9:07 am
    • March 2, 2009 at 9:53 am
    • Rene
      March 2, 2009 at 12:07 pm
    • Rene
      March 2, 2009 at 12:30 pm
      • March 2, 2009 at 2:18 pm
      • March 5, 2009 at 10:42 am
  8. Teresa
    March 2, 2009 at 11:08 am
  9. March 2, 2009 at 12:09 pm
    • March 2, 2009 at 1:15 pm
  10. Marc
    March 2, 2009 at 12:57 pm
    • Rene
      March 2, 2009 at 1:07 pm
  11. Teresa
    March 2, 2009 at 1:51 pm
  12. oneroux
    March 3, 2009 at 4:35 pm
  13. March 4, 2009 at 10:40 am
  14. March 4, 2009 at 1:01 pm
  15. March 4, 2009 at 1:14 pm
  16. March 4, 2009 at 1:33 pm
  17. insub2
    March 4, 2009 at 5:17 pm
    • insub2
      March 4, 2009 at 5:31 pm
  18. March 22, 2009 at 12:27 pm
  19. ozan
    March 24, 2009 at 12:35 pm
  20. April 6, 2009 at 6:52 am
  21. dspinoz
    April 24, 2009 at 7:03 pm
  22. April 30, 2009 at 11:29 am
  23. mc
    May 2, 2009 at 11:26 pm
  24. May 3, 2009 at 1:31 pm
  25. mc
    May 3, 2009 at 11:58 pm
  26. May 13, 2009 at 4:44 am
  27. Al
    June 4, 2009 at 2:27 pm
    • Al
      June 4, 2009 at 2:58 pm
  28. June 7, 2009 at 6:53 am
  29. June 16, 2009 at 8:46 am
  30. July 19, 2009 at 4:17 pm
  31. rajat
    September 1, 2009 at 12:35 am
  32. rajat
    September 1, 2009 at 2:12 am
  33. vikas
    September 1, 2009 at 6:37 am
  34. jake
    September 2, 2009 at 11:28 am
  35. September 6, 2009 at 11:08 pm
  36. kapil
    September 9, 2009 at 6:37 am
  37. October 10, 2009 at 11:16 am
  38. October 11, 2009 at 11:46 am
  39. praveen
    October 18, 2009 at 7:28 am
    • Amin
      February 27, 2010 at 11:04 am
  40. October 21, 2009 at 10:44 am
  41. October 22, 2009 at 4:57 am
  42. supremasi
    October 30, 2009 at 11:41 pm
  43. sandy
    November 9, 2009 at 9:34 am
  44. adi
    December 15, 2009 at 5:05 pm
  45. December 29, 2009 at 11:37 pm
  46. January 5, 2010 at 7:19 pm
  47. bp
    March 4, 2010 at 8:26 am

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Popular Series

Output Buffering Articles
Build a Custom AJAX and PHP Contact Form
The Ultimate Image Gallery Manager.
ThemeForest Premium Site and WordPress Templates