How can I create a Searchstring for a Google AJAX Search API?

Posted by elmaso on Stack Overflow See other posts from Stack Overflow or by elmaso
Published on 2010-04-03T15:09:37Z Indexed on 2010/04/03 15:13 UTC
Read the original article Hit count: 242

Filed under:
|
|
|

Hello, i have this code to get the search resutls from the api:

querygoogle.php:

<?php
session_start();



// 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&start=20&q=' . urlencode('' . $_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 = 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;
?>

search.php

<?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']);
}
?>

but with this code, I cant add a searchstring.. how can i add a search string like search.php?search=keyword ?

thanks

© Stack Overflow or respective owner

Related posts about google

Related posts about php