【问题标题】:How can I create a Searchstring for a Google AJAX Search API?如何为 Google AJAX 搜索 API 创建搜索字符串?
【发布时间】:2011-02-04 00:33:49
【问题描述】:

我有这段代码可以从 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']);
}
?>

但是使用此代码,我无法添加搜索字符串.. 如何添加像 search.php?search=keyword 这样的搜索字符串?

谢谢

【问题讨论】:

    标签: php json api


    【解决方案1】:

    好的,吃吧!改成这段代码:

    querygoogle.php

    $_SESSION['googleresults'] = $formattedresults;
    header("Location: search.php?searchquery=" . $_GET['searchquery']);
    exit;
    
    ... &start=20&q=' . urlencode('' . $_GET['searchquery']);
    

    search.php

    <form method="get" action="querygoogle.php">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多