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

所属分类: 网络编程 / PHP编程 阅读数: 437
收藏 0 赞 0 分享

http://code.google.com/apis/ajaxsearch/documentation/#fonje

复制代码 代码如下:

// 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 = 'https://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>';

更多精彩内容其他人还在看

解决laravel中日志权限莫名变成了root的问题

今天小编就为大家分享一篇解决laravel中日志权限莫名变成了root的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Laravel框架中集成MongoDB和使用详解

今天小编就为大家分享一篇Laravel框架中集成MongoDB和使用详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

浅谈laravel框架sql中groupBy之后排序的问题

今天小编就为大家分享一篇浅谈laravel框架sql中groupBy之后排序的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

mac pecl 安装php7.1扩展教程

今天小编就为大家分享一篇mac pecl 安装php7.1扩展教程,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Mac下关于PHP环境和扩展的安装详解

今天小编就为大家分享一篇Mac下关于PHP环境和扩展的安装详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

laravel 解决groupBy时出现的错误 isn't in Group By问题

今天小编就为大家分享一篇laravel 解决groupBy时出现的错误 isn't in Group By问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Laravel 框架返回状态拦截代码

今天小编就为大家分享一篇Laravel 框架返回状态拦截代码,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

在laravel框架中实现封装公共方法全局调用

今天小编就为大家分享一篇在laravel框架中实现封装公共方法全局调用,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

在Laravel 的 Blade 模版中实现定义变量

今天小编就为大家分享一篇在Laravel 的 Blade 模版中实现定义变量,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享

Laravel基础_关于view共享数据的示例讲解

今天小编就为大家分享一篇Laravel基础_关于view共享数据的示例讲解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
收藏 0 赞 0 分享
查看更多