用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根据ip查询所在地区(非常有用,赶集网就用到)

dat文件,关于ip对应地区的信息文件qqwry.dat文件网上自己下载class类文件,解析qqwry.data文件的IpLocation.php文件复制代码 代码如下:<?ph...

PHP中imagick函数的中文解释

imagick的:: adaptiveBlurImage - 增加了自适应模糊滤镜图像  imagick的:: adaptiveResizeImage - 自适应调整图像数据...

PHP框架Laravel插件Pagination实现自定义分页

Laravel 的分页很方便,其实扩展起来也挺容易的,下面就来做个示例,扩展一下 paginate() 和 simplePaginate() 方法,来实现我们自定义分页样式,比如显示 "...

PHP下载远程图片的几种方法总结

PHP下载远程图片的几种方法总结 本文演示3个从远程URL下载图片,并保存到本地文件中的方法,包括file_get_contents,curl和fopen。 1. 使用file_get...

PHP判断文件是否存在、是否可读、目录是否存在的代码

1、案例: 复制代码 代码如下: <?php $file = 'jb51.net.php'; if (is_readable($file) == false) { die('文件不...