欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-07-03 12:22:44
复制代码 代码如下: // this example request includes an optional api key which you will need t...


复制代码 代码如下:

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