用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 cookie工作原理与实例详解

在php 中cookie是我们常用到的,但是可能很多朋友都不知道cookie是怎么工作的,下面小编来给大家整理一下关于php cookie 工作原理与一些对于cookie读写操作实例。...

asp.net访问网络路径方法(模拟用户登录)

核心代码: public class IdentityScope : IDisposable { // obtains user token [DllImport("...

浅谈PHP变量作用域以及地址引用问题

作用域的概念: 在PHP脚本的任何位置都可以声明变量,但是,声明变量的位置会大大影响访问变量的范围。这个可以访问的范围称为作用域。 主要的常用的包括:局部变量、全局变量、静态变量。 1、...

PHP入门教程之自定义函数用法详解(创建,调用,变量,参数,返回值等)

本文实例讲述了PHP自定义函数用法。分享给大家供大家参考,具体如下: Demo1.php <?php //标准函数,内置函数 echo md5('123456'...