当前位置:Gxlcms > PHP教程 > 用PHP获取GoogleAJAXSearchAPI数据的代码_php技巧

用PHP获取GoogleAJAXSearchAPI数据的代码_php技巧

时间:2021-07-01 10:21:17 帮助过:9人阅读

http://code.google.com/apis/ajaxsearch/documentation/#fonje
代码如下:
  1. <br>// This example request includes an optional API key which you will need to <br>// remove or replace with your own key. <br>// Read more about why it's useful to have an API key. <br>// The request also includes the userip parameter which provides the end <br>// user's IP address. Doing so will help distinguish this legitimate <br>// server-side traffic from traffic which doesn't come from an end-user. <br>$url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&" <br>. "q=Paris%20Hilton&key=INSERT-YOUR-KEY&userip=USERS-IP-ADDRESS"; <br><br>// sendRequest <br>// note how referer is set manually <br>$ch = curl_init(); <br>curl_setopt($ch, CURLOPT_URL, $url); <br>curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); <br>curl_setopt($ch, CURLOPT_REFERER, /* Enter the URL of your site here */); <br>$body = curl_exec($ch); <br>curl_close($ch); <br><br>// now, process the JSON string <br>$json = json_decode($body); <br>// now have some fun with the results... <br> <br>API KEY 申请地址: <br>http://code.google.com/apis/ajaxsearch/signup.html <br><br>由此,我们可以写个函数像这样 <br><span><u></u></span> 代码如下:<pre class="brush:php;toolbar:false layui-box layui-code-view layui-code-notepad"><ol class="layui-code-ol"><li><br>function google_search_api($args, $referer = 'http://www.gxlcms.com/', $endpoint = 'web'){ <br>$url = "http://ajax.googleapis.com/ajax/services/search/".$endpoint; <br>if ( !array_key_exists('v', $args) ) <br>$args['v'] = '1.0'; <br>$url .= '?'.http_build_query($args, '', '&'); <br>$ch = curl_init(); <br>curl_setopt($ch, CURLOPT_URL, $url); <br>curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); <br>curl_setopt($ch, CURLOPT_REFERER, $referer); <br>$body = curl_exec($ch); <br>curl_close($ch); <br>return json_decode($body); <br>} <br><br>// 使用示例 <br>$rez = google_search_api(array( <br>'q' => '21andy.com', // 查询内容 <br>'key' => '你申请到的API KEY', <br>'userip' => '你的IP地址', <br>)); <br>header('Content-type: text/html; charset=utf-8;'); <br>echo '<xmp>'; <BR>print_r($rez); <BR>echo '</xmp>'; <br> </li></ol></pre>

人气教程排行