Search Here

October 25, 2009

PHP Tip: Add Custom Google Search Results to Your Site with PHP

Have you ever wanted to integrate a custom google search on your site, and style it to your liking? Today, I 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.
1.<form method="post" action="querygoogle.php">
2.<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" />
3.</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
01.<?php
02.session_start();
03.  
04.// if you use an Mike Migurski's JSON library, include it like I did
05.require_once('JSON.phps');
06.  
07.// Here's the Google AJAX Search API url for curl. It uses Google Search's site:http://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
08.  
09.$url = 'http://ajax.googleapis.com/ajax/services/search/web?rsz=large&;v=1.0&q=' . urlencode('site:' . $_SERVER['HTTP_HOST'] . ' ' . $_POST['searchquery']);
10.  
11.// use fopen and fread to pull Google's search results
12.  
13.$handle = fopen($url, 'rb');
14.$body = '';
15.while (!feof($handle)) {
16.$body .= fread($handle, 8192);
17.}
18.fclose($handle);
19.  
20.// now $body is the JSON encoded results. We need to decode them.
21.  
22.$json = new Services_JSON();
23.$json = $json->decode($body);
24.  
25.// now $json is an object of Google's search results and we need to iterate through it.
26.  
27.foreach($json->responseData->results as $searchresult)
28.{
29.if($searchresult->GsearchResultClass == 'GwebSearch')
30.{
31.$formattedresults .= '
32.<div class="searchresult">
33.<h3><a href="' . $searchresult->unescapedUrl . '">' . $searchresult->titleNoFormatting . '</a></h3>
34.<p class="resultdesc">' . $searchresult->content . '</p>
35.<p class="resulturl">' . $searchresult->visibleUrl . '</p>
36.</div>';
37.}
38.}
39.  
40.$_SESSION['googleresults'] = $formattedresults;
41.header('Location: ' . $_SERVER['HTTP_REFERER']);
42.exit;
43.?>

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):
01.&lt;?php
02.session_start();
03.?&gt;
04.  
05.<form method="post" action="querygoogle.php">
06.<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" />
07.</form>
08.  
09.&lt;?php
10.if(!emptyempty($_SESSION['googleresults']))
11.{
12.echo $_SESSION['googleresults'];
13.unset($_SESSION['googleresults']);
14.}
15.?&gt;
Your search results work! But they're ugly. Here's some sexy CSS like I promised to get your started.
01.body
02.{
03.background-color: #000;
04.color: #ccc;
05.font: .75em/1.5em Arial, sans-serif; /* EMs calculated with pxtoem.com */
06.padding: 1.5em;
07.margin: 0;
08.width: 40em;
09.}
10.  
11..searchresult
12.{
13.padding: 1.5em 0;
14.border-bottom: 1px solid #333;
15.}
16.  
17..searchresult h3, .searchresult p
18.{
19.margin: 0;
20.}
21.  
22..searchresult h3 a
23.{
24.font: italic 1em Georgia, serif;
25.color: #f30;
26.border-bottom: 1px solid #900;
27.text-decoration: none;
28.font-weight: bold;
29.font-size: 1em;
30.}
31.  
32..searchresult .resultdesc b
33.{
34.color: #fff;
35.}
36.  
37..searchresult .resulturl
38.{
39.color: #666;
40.font-size: .75em;
41.}
If you'd like to style your own results your way, each result will be placed in the following HTML format:
1.<div class="searchresult">
2.<h3><a href="page-url">Page Title</a></h3>
3.<p class="resultdesc">Page description/highlights</p>
4.<p class="resulturl">URL that google always shows in green</p>
5.</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!

No comments:

Post a Comment