用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实现的常见排序算法汇总

本文汇总了常见的php排序算法,在进行算法设计的时候有不错的借鉴价值。现分享给大家供参考之用。具体如下: 一、插入排序 用文字简单的描述,比如说$arr = array(4,2,4,6,...

php的ddos攻击解决方法

本文实例讲述了php的ddos攻击解决方法。分享给大家供大家参考。具体分析如下: 今天自己的一台机器突然向外部发送大量数据包,可每秒到1G以上,虽然我用策略把UDP禁止包是发不出去但是很...

php 获得汉字拼音首字母的函数

php获取汉字拼音的第一个字母复制代码 代码如下:<?php function getinitial($str) { $asc=ord(substr($str,0,1)); if...

PHP实现redis限制单ip、单用户的访问次数功能示例

本文实例讲述了PHP实现redis限制单ip、单用户的访问次数功能。分享给大家供大家参考,具体如下: 有时候我们需要限制一个api或页面访问的频率,例如单ip或单用户一分钟之内只能访问多...

smarty中先strip_tags过滤html标签后truncate截取文章运用

strip_tags() 函数剥去 HTML、XML 以及 PHP 的标签。 复制代码 代码如下: <?php echo strip_tags(“Hello <b>wo...