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

yipeiwu_com5年前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中date与gmdate的区别及默认时区设置

一、date与gmdate有什么区别?PHP时间函数中有两个格式化函数:date()和gmdate(),在官方的文档中的描述为:复制代码 代码如下:date()  ...

PHP加速 eAccelerator配置和使用指南

前一段时间完成了服务器从FreeBSD4.10到6.1的升级,同时把PHP也升级到了最新的PHP5.1.4,Apache也升级到了最新的Apache2.2,为了更好的提高系统的性能考虑对...

php版银联支付接口开发简明教程

本文实例讲述了php版银联支付接口开发的方法。分享给大家供大家参考,具体如下: 支付接口现在有第三方的支付接口也有银行的支付接口。这里就来介绍php版本银联支付接口开发的方法。 银联支付...

php对象和数组相互转换的方法

本文实例讲述了php对象和数组相互转换的方法。分享给大家供大家参考。具体分析如下: 这里定义2个php匿名对象和数组相互转换的函数,代码如下: function array2obje...

php部分常见问题总结

目录: 1:为什么我得不到变量 2:调试你的程序 3:如何使用session 4:为什么我向另一网页传送变量时,只得到前半部分,以空格开头的则全部丢失 5:如何截取指定长度汉字而不会出现...