Home     Contact us

Customized Google Search engine in PHP

jhnidk - June 8th, 2010 in: PHP

Create a customized Google Search for your siteGoogle has a great AJAX API for integrating Google search on your own site.

However if you want to tweak layout and functionality, the AJAX API can be difficult to work with.

In this post we’ll build a Google Powered web search in PHP, where you can customize the look and feel anyway you like, and easily add enhanced functionality like screenshots, or whatever is relevant for your site.

Restful Google API

The AJAX API has it’s benefits. You just implement a few lines of code on your site, and then you have a web search on your site.

But if you want to embed additional data in the search result, or want to change the layout of the search result, track clicks etc, the AJAX API has it’s limitations.

The good news is that Google also offers a Restful API, that enables you to retrieve search results as a JSON object.

When using the Restful API your application needs to follow these guidelines:

  • The application needs to follow the normal Search API guidelines
  • A application key is not required but appreciated
  • The application MUST always include a valid and accurate http referer header in the requests

To ensure that a valid HTTP header is included in all requests, we’ll call the Restful API through the curl functions in PHP:

$pageurl="www.yoursite.com";
<pre>$keyword=urlencode($keyword);
$url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=small&lr=lang_en&filter=0&q=$keyword";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, "$pageURL");
$body = curl_exec($ch);
curl_close($ch);
</pre>

The result from this request is returned as a JSON object. To parse and print out the object on the page, we’ll use the following code:

$json = json_decode($body);
 foreach ($json->responseData->results as $node) {
 $name = $node->titleNoFormatting;
 $name = utf8_decode($name);
 $url = $node->url;
 $desc = $node->content;
 $desc = utf8_decode($desc);
 echo ("<b>$name</b></b><br/>$desc<br/><a href=\"$url\" >($url)</a><br/>");
 }

As you can see you can do all kinds of interesting stuff with the output data from the JSON object.

The final script

To create a full script and illustrate the possibilities, I have included the above code snippets in a empty page and  included thumbnails from the free thumbnail service: Thumbalizr.com.

<?
if (isset($keyword)) {
 if (!isset($start)) {
 $start='0';
}
$pageurl="www.yoursite.com";
$keyword=urlencode($keyword);
 $url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&start=$start&lr=lang_en&filter=0&q=$keyword";
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_REFERER, "$pageURLt");
 $body = curl_exec($ch);
 curl_close($ch);
}
?>
<html>
<head>
 <title>Custom Google search engine</title>
</head>
<body>
<form action="<?php echo $PHP_SELF;?>" method="get">

<input name="keyword"  type="text"  value="<? echo $keyword; ?>"/><input type="submit" value="Search"  /><br/><br/>

<?
if (isset($keyword)) {
 $json = json_decode($body);
 $count = $start;
 echo ("<table width=\"500\">");
 foreach ($json->responseData->results as $node) {
 $count++;
 $name = $node->titleNoFormatting;
 $name = utf8_decode($name);
 $url = $node->url;
 $parse = parse_url($url);
 $img_url = $parse['host'];
 $desc = $node->content;
 $desc = utf8_decode($desc);
 echo ("<tr><td valign=\"top\"><img src=\"http://api.thumbalizr.com/?url=$img_url&width=100\"/><br/></td><td><a href=\"$url\" ><b>$name</b></a></b><br/>$desc<br/><a href=\"$url\" >($url)</a><br/><br/></td></tr>");
 }
 echo ("</table>");

if ($start >= 9) { // link to previous page
 $pre = $start-8;
 echo ("<a href=\"google_custom_search.php?keyword=$keyword&start=$pre\">previous page</a> ");
}

if ($count-8 >= $start) {  // link to next page
 $nxt = $count+1;
 echo (" <a href=\"google_custom_search.php?keyword=$keyword&start=$nxt\">next page</a>");
}
}

?>
</form>
</body>
</html>

You can try the final search engine here: example.

Recommended further reading:


Web Development Solutions: Ajax, APIs, Libraries, and Hosted Services Made easy Web Development Solutions: Ajax, APIs, Libraries, and Hosted Services Made easy

Building “Web 2.0″/Ajax” applications is all the rage right now, and there is a lot of complicated code involved, but a lot of budding web developers don’t realize that most of the hard work is already done for them, and…


Accelerated DOM Scripting with Ajax, APIs, and Libraries (Expert's Voice) Accelerated DOM Scripting with Ajax, APIs, and Libraries (Expert’s Voice)

JavaScript is one of the hottest web development technologies around, and DOM Scripting is a very important subset of JavaScript, which specifically allows developers to add dynamic functionality to their web applications. Interest in this subject is…


Beginning Google Maps API 3 Beginning Google Maps API 3

This book is about the next generation of the Google Maps API. It will provide the reader with the skills and knowledge necessary to incorporate Google Maps version 3 on web pages in both desktop and mobile browsers. It also…

17 Responses to “Customized Google Search engine in PHP”

  1. Finally, I found what I’m looking for. Thank you for sharing.


    putude
  2. super article, very useful thanks.

    unfortunately exact code return a blank page, is there any update/config necessary ?
    do you have complete code?
    thanks!


    shmek erosul
  3. I’m sorry, there was a small typo in the code. It has been updated now. Thank you for giving feedback :-)


    jhnidk
  4. hi,

    i tried this code but i didn’t get the results can you please send me the revised code. it helps me a lot i want to fetch the all google results
    please send me the revised code. if send means i appriciate you.


    ramakrishna
  5. unfortunately exact code return a blank page, is there any update/config necessary ?
    do you have complete code?
    thanks!


    ramakrishna
  6. The code works now. In line 44, wordpress replaced the code <8) with a smiley….


    jhnidk
  7. hi jhnidk,

    thanks for your immidiate response and giving the revised code but unfortunately it gives the empty page, so could you please give the exact code that is what i am saw in the example demo,if giving that exact code means it helps me a lot.
    and i have a one doubt in line “6″ you mentioned $pageurl=”www.yoursite.com”; here i put the
    http://localhost/websiterankingssoftware/google/google_custom_search.php since i am running in localhost so i put that url is it correct?
    please help me .

    thanks&regards
    ramakrishna.


    ramakrishna
  8. hi jhnidk,

    I think that there is some problem in this code even i print the
    result the results are not shown
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_REFERER, “$pageURLt”);
    $body = curl_exec($ch);
    print_r($body).”results”;
    curl_close($ch);
    and also i write the statement after
    if (isset($keyword)) {
    echo “raj”;
    if (!isset($start)) {
    $start=’0′;
    }
    but it not displayed even “raj” also. same like that
    echo “ramakrishna.””;
    $pageurl=”http://localhost/websiterankingssoftware/google/google_custom_search.php”;
    $keyword=urlencode($keyword);
    echo “search”;
    but it not displayed “ramakrishna” and “search” also could you please help me. i am awaiting for ur reply.
    thanks and regards
    ramakrishna.


    ramakrishna
  9. Hi again

    I think there is a bug in the code presentation tool. If you select the “view cource” option in the upper right corner of the code display module, and copy and paste the code from this new code preview window it works.

    You’re properly getting the blank page because PHP error codes are disabled in your installation? – Normally you would get a PHP error message, saying that there is a syntax error in the code.


    jhnidk
  10. You should use your “external url” as pageurl: eg: “http://www.yoursite.com/create_a_google_search”


    jhnidk
  11. hi jhnidk,

    i think ajax api is not correct so thats why it’s not displaying the
    results i need this requirement please send me the exact code if you give me the exact code i.e i shown in the demo(example) of this site means it will helps me a lot.

    thanks
    regards
    ramakrishna.


    ramakrishna
  12. hi,

    i think that you are in online is it necessary to write the code in two php tags? even i select the select the “view source” code it is not working
    form begining onwords i selected the “viewsource” code only but it is not working could you please give me the exact code please it helps me a lot.


    ramakrishna
  13. hi

    please tell me in which line error is there is it code is complete code
    or we need to write some code if you tell means i will follow for forther step how to do that program and how to get the results.
    thanks and regards
    ramakrishna


    ramakrishna
  14. Hi,

    Try this code – and maybe turn on PHP error messages in your PHP configuration, so it’s easier to see where any errors might occur in your script :-)

    Custom Google search engine

    <form action="” method=”get”>

    <input name="keyword" type="text" value="”/>

    <?
    if (isset($keyword)) {
    $json = json_decode($body);
    $count = $start;
    echo ("”);
    foreach ($json->responseData->results as $node) {
    $count++;
    $name = $node->titleNoFormatting;
    $name = utf8_decode($name);
    $url = $node->url;
    $parse = parse_url($url);
    $img_url = $parse['host'];
    $desc = $node->content;
    $desc = utf8_decode($desc);
    echo (“$name$desc($url)“);
    }
    echo (“”);

    if ($start >= 9) { // link to previous page
    $pre = $start-8;
    echo (“previous page “);
    }

    if ($count-8 >= $start) { // link to next page
    $nxt = $count+1;
    echo (” next page“);
    }
    }

    ?>


    jhnidk
  15. hi,
    thanks for your reply and your patience, i tried that code but even it don’t display any results i think ajax api has some bug so it can’t display any results even i echo the result it can’t display. if we echo the reult means it will display google page but it can’t display anything so i think it is the problem please give me the correct code sir. i am awaiting for your reply
    warm regards
    ramakrishna


    ramakrishna
  16. hi jhnidk,

    could you please give me the exact code of this
    warmregards
    ramakrishna


    ramakrishna

Trackbacks

  1. Virtual Crowds

Leave a Reply

Copyright © 2012 Tips4php.net - Recent entries RSS feedEntries RSS Log in