当前位置: 移动技术网 > IT编程>开发语言>PHP > 用PHP获取Google AJAX Search API 数据的代码

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

2019年05月27日  | 移动技术网IT编程  | 我要评论


复制代码 代码如下:

// 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 申请地址:


由此,我们可以写个函数像这样
复制代码 代码如下:

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网