用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学习笔记 用户注册模块用户类以及验证码类

所以,把第一章,可重用类的代码贴出来,便于以后查阅以及供给有需要的朋友。 :User类,包括读取和设置数据库,以及保存更改交互 复制代码 代码如下: <?php class Use...

php中批量修改文件后缀名的函数代码

复制代码 代码如下:<?php function foreachDir($path){ $handle=opendir($path); if($handle){ while (fa...

WordPress判断用户是否登录的代码

is_user_logged_in() 说明 根据当前访问者是否登录返回布尔值true或false。 参数 该函数不接受任何参数。 用法 复制代码 代码如下: <?php if (...

PHP采用自定义函数实现遍历目录下所有文件的方法

目录的遍历是PHP程序设计中经常会用到的一个功能,很多PHP项目都有这一功能模块。今天本文就来实例解析一下PHP采用自定义函数实现遍历目录下所有文件的方法。具体方法如下: 方法一:使用r...

PHP接口多继承及tarits实现多继承效果的方法

本文实例讲述了PHP接口多继承及tarits实现多继承效果的方法。分享给大家供大家参考,具体如下: 接口多继承 在PHP的面向对象中,接口可以继承接口。PHP类只能继承一个父类(单继承)...