用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基于闭包思想实现的BT(torrent)文件解析工具实例详解

本文实例讲述了PHP基于闭包思想实现的torrent文件解析工具。分享给大家供大家参考,具体如下: PHP对静态词法域的支持有点奇怪,内部匿名函数必须在参数列表后面加上use关键字,显式...

php实现将数组转换为XML的方法

php实现将数组转换为XML的方法

本文实例讲述了php实现将数组转换为XML的方法。分享给大家供大家参考。具体如下: 1. php代码如下: <?php class A2Xml { private...

关于URL最大长度限制的相关资料查证

在开发调试支付宝接口时,突然发现支付宝接口的URL很长,远远大于之前自己印象中的255个字符。赶紧搜索查证了一番,理解如下: URL不能大于255bytes的说法确实存在,在RFC261...

ie6 动态缩略图不显示的原因

我在上传生成缩略图时,缩略图显示的链接如下; 复制代码 代码如下:< img src ="/index.php?action=sys_upload_showThumb&id=bdc...

php使用高斯算法实现图片的模糊处理功能示例

php使用高斯算法实现图片的模糊处理功能示例

本文实例讲述了php使用高斯算法实现图片的模糊处理功能。分享给大家供大家参考,具体如下: <?php class image_blur{ function gau...