用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>';

相关文章

phpmyadmin显示utf8_general_ci中文乱码的问题终级篇

phpmyadmin显示utf8_general_ci中文乱码的问题终级篇

自己写PHP也有一年多了,然后编码问题却老是没有得到好的解决,自己的情况是这样的, 网页显示完全正常,在phpmyadmin数据库显示中文乱码,不管是简体还是繁体,只要是中文都是如下显示...

关于初学PHP时的知识积累总结

PHP基础一、初识PHPPHP是与HTML混合使用的嵌入式语言。1、PHP标记默认标记<?php ?> 短标记<? ?>,需在php.ini中将short_ope...

修改Laravel5.3中的路由文件与路径

前言 大家可能没有注意到, 在 Laravel 4 以及更老版本中, 路由逻辑是性能上的一个瓶颈--特别是对于有很多路由定义的应用而言. 一个只有几百条路由定义的 Laravel 站点...

PHP中的Session对象如何使用

在PHP开发中对比起Cookie,session 是存储在服务器端的会话,相对安全,并且不像 Cookie 那样有存储长度限制。下面则是对Session的介绍。 php中的Session...

php实现的三个常用加密解密功能函数示例

php实现的三个常用加密解密功能函数示例

本文实例讲述了php实现的三个常用加密解密功能函数。分享给大家供大家参考,具体如下: 算法一: //加密函数 function lock_url($txt,$key='www.jb5...