如何使用PHP和Google API在特定网站中进行搜索


How can I search within a specific website with PHP and the Google API?

如何使用PHP和Google API在特定网站中进行搜索?当我搜索关键字时,我希望从website1.comwebsite2.comwebsite3.com中获得结果。例如:

<input name="search" value="keyword"> 
<input name="as_site" value="site1.com"> 
<input name="as_site" value="site2.com">
<input name="as_site" value="site3.com">

结果应仅从这三个网站返回。

注意:Google 网页搜索 API 已于 2010 年 11 月 1 日正式弃用。它>将继续按照我们的弃用政策工作,但您每天>可以发出的请求数量将受到限制。因此,我们鼓励你迁移到新的自定义搜索 API。

根据您的表单并假设关键字字段命名keyword此示例代码假设您只有一个要搜索的网站,您可以自定义它以包含多个站点。假设站点输入名为 site

// The request also includes the userip parameter which provides the end
// user's IP address. Doing so will help distinguish this legitimate
// server-side traffic from traffic which doesn't come from an end-user.
$query = $_POST['keyword'];
$site = $_POST['site'];
$url = "https://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
    . "q={$query}+Site:{$site}&userip=USERS-IP-ADDRESS";
// sendRequest
// note how referer is set manually
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, /* Enter the URL of your site here */);
$body = curl_exec($ch);
curl_close($ch);
// now, process the JSON string
$json = json_decode($body);
// now have some fun with the results...