用PHP获取Google AJAX Search API 数据的代码

yipeiwu_com4年前PHP代码库

http://code.google.com/apis/ajaxsearch/documentation/

复制代码 代码如下:

// This example request includes an optional API key which you will need to
// remove or replace with your own key.
// Read more about why it's useful to have an API key.
// 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.
$url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
. "q=Paris%20Hilton&key=INSERT-YOUR-KEY&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...

API KEY 申请地址:
http://code.google.com/apis/ajaxsearch/signup.html

由此,我们可以写个函数像这样
复制代码 代码如下:

function google_search_api($args, $referer = '//www.jb51.net/', $endpoint = 'web'){
$url = "http://ajax.googleapis.com/ajax/services/search/".$endpoint;
if ( !array_key_exists('v', $args) )
$args['v'] = '1.0';
$url .= '?'.http_build_query($args, '', '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $referer);
$body = curl_exec($ch);
curl_close($ch);
return json_decode($body);
}

// 使用示例
$rez = google_search_api(array(
'q' => '21andy.com', // 查询内容
'key' => '你申请到的API KEY',
'userip' => '你的IP地址',
));
header('Content-type: text/html; charset=utf-8;');
echo '<xmp>';
print_r($rez);
echo '</xmp>';

相关文章

PHP curl CURLOPT_RETURNTRANSFER参数的作用使用实例

获取页面内容,不直接输出到页面,CURLOPT_RETURNTRANSFER参数设置    使用PHP curl获取页面内容或提交数据,有时候希望返回的内容...

dede3.1分页文字采集过滤规则详说(图文教程)续二

dede3.1分页文字采集过滤规则详说(图文教程)续二

稍微了解dede采集规则的朋友上篇内容完全可以略过,下面看看如何以静制动、以不变就万变地解决分页采集问题。二、采集新目标目标地址:1、http://www.tiansou.net/Htm...

php和html的区别点详细总结

今天我来和大家讨论下关于PHP技术的另一个简单小问题,就是PHP代码和HTML代码的区别在哪里。 其实,如果简单的说,大家都知道,HTML是典型的静态网络编程用语,而PHP则是一种可实现...

PHP5函数小全(分享)

很多PHP前辈都写了PHP大全,但是我看了发现那些所谓的“大全”根本就不全,甚至比我整理的这个列表内的函数还要少,竟然冠名“大全”,让我不愤,背道而驰,整个“小犬”。usleep() 函...

Windows下安装Memcached的步骤说明

(其实在Windows下安装还是比较简单的) 源码包准备: 1,memcached 1.2.1 for Win32 binaries 这个是 Win32 服务器端的 memcached...