本文將介紹如何使用GoogleCustom Search API,調用Google的搜索結果。最後提供了一個用PHP編寫的簡單示例。
一、獲取Google的授權
1.註冊Google帳號,網址鏈接:https://accounts.google.com/NewAccount。
2.開啓Custom Search功能:打開網址https://code.google.com/apis/console→在services菜單中開啓Custom Search API功能→ 在API Access菜單中獲取相應的API Key。
3.創建基於Google Custom Search的應用:打開網址http://www.google.com/cse/manage/create→填寫表單並提交(Sites to search一欄是Google搜索的網址,所以如果要搜索整個互聯網,就需要將互聯網所有網址輸進去)→ 獲取應用的ID(即請求參數中的cx參數)。
二、Google Custom Search API使用流程
1.發送數據請求。Google Custom Search API的使用採用GET請求方式,請求的URL爲https://www.googleapis.com/customsearch/v1?cx={APP ID}&key={API Key}&q={key word}
其中還用得上的參數有start(返回的第一條搜索結果的標號,默認值是1)、num(一次返回的搜索結果條數,範圍是1-10,默認是10)。具體的請求參數請參見鏈接https://developers.google.com/custom-search/v1/using_rest#st_params。
2.獲取請求返回的結果。請求返回的結果有兩種數據格式,JSON和Atom,默認情況下返回的是JSON格式的數據。
3.解析返回的結果。PHP、Python、Java等都有解析JSON的庫文件,可以直接解析返回的搜索結果。
三、PHP調用Custom Search API示例
<html>
<body>
<?php
// 初始化一個 cURL 對象
$curl = curl_init();
$key = '*******************************';
$cx = '********************************';
$q = 'english';
$url = 'https://www.googleapis.com/customsearch/v1?'.'cx='.$cx.'&key='.$key.'&q='.$q;
// 設置你需要抓取的URL
curl_setopt($curl, CURLOPT_URL, $url);
// 設置header
curl_setopt($curl, CURLOPT_HEADER, 0);
// 設置cURL 參數,要求結果保存到字符串中還是輸出到屏幕上。
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
// 運行cURL,請求網頁
$data = curl_exec($curl);
// 關閉URL請求
curl_close($curl);
// 顯示獲得的數據
//var_dump($data);
// Parse json data
$json = json_decode($data);
if(isset($json)) {
echo $json->items[0]->title;
} else {
echo 'json is null.';
}
?>
</body>
</html>