用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获取给定日期相差天数的方法分析

本文实例讲述了php获取给定日期相差天数的方法。分享给大家供大家参考,具体如下: 方法一: <?php function count_days($a,$b){ $a...

完美解决dedecms中的[html][/html]和[code][/code]问题

终于解决了完美解决dedecms中的[html][/html]和[code][/code]问题,因为我的php不太熟练,所以正则搞了好几天,才能好,这次主要修改了discuz5.5和de...

如何在php中正确的使用json

从5.2版本开始,PHP原生提供json_encode()和json_decode()函数,前者用于编码,后者用于解码。 1、json_encode()该函数主要用来将数组和对象,转换为...

PHP实现大数(浮点数)取余的方法

本文实例讲述了PHP实现大数(浮点数)取余的方法。分享给大家供大家参考,具体如下: 一般我们进行取余运算第一个想到的就是用百分号%,但当除数是个很大的数值,超出了int范围时,这样取余就...

php skymvc 一款轻量、简单的php

改框架主要用于实现多个程序员之间的协同开发以及mvc开发模式的实现.skymvc采用mvc开发方式,框架本身易扩展。skymvc作为天网计划的基础框架,秉承易用、易学、共同开发的优良传统...