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

yipeiwu_com6年前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随机生成信用卡卡号的方法

本文实例讲述了PHP随机生成信用卡卡号的方法。分享给大家供大家参考。具体分析如下: 这段PHP代码根据信用卡卡号产生规则随机生成信用卡卡号,是可以通过验证的,仅供学习参考,请不要用于非法...

PHP迭代与递归实现无限级分类

PHP迭代与递归实现无限级分类

无限级分类是开发中常见的情况,因此本文对常见的无限极分类算法进行总结归纳. 1.循环迭代实现 $arr = [ 1=>['id'=>1,'name'=>'父1'...

PHP Token(令牌)设计

PHP Token(令牌)设计

如何达到目的: 怎样避免重复提交? 在SESSION里要存一个数组,这个数组存放以经成功提交的token.在后台处理时,先判断这个token是否在这个数组里,如果存在,说明是重复提交.&...

nginx+thinkphp下解决不支持pathinfo模式

nginx环境问题弄了两天,发现网上很多人的帖子要么复制粘贴,要么就是没有结贴,还自己写一句“哈哈,我自己解决了”之类的,这点我就鄙视这些发帖的同胞了,你说你问题问了,问题解决了也不给个...

PHP实现重载的常用方法实例详解

本文实例讲述了PHP实现重载的常用方法。分享给大家供大家参考,具体如下: php是弱类型语言,并没有像JAVA这种强类型语言一样有重载。 重载一般来说就是拥有相同的函数名或方法名,但是参...