Google AJAX Search API(已停止維護,現建議使用 Custom Search JSON API)曾提供簡易的 REST 介面供伺服器端直接查詢。本文示範如何使用 PHP cURL 發送請求、設定 Referer 標頭、解析 JSON 回應並提取搜尋結果。
<?php
/**
* 簡易 Google 搜尋封裝
* @param string $query 搜尋關鍵字
* @param string $referer 您的網站網址(API 要求)
* @return array 搜尋結果陣列
*/
function googleSearch(string $query, string $referer = 'https://www.example.com'): array
{
$url = 'https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=' . urlencode($query);
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_REFERER => $referer, // 必填:識別呼叫來源
CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; PHP Script)',
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => true, // 生產環境請保持 true
]);
$body = curl_exec($ch);
if ($body === false) {
throw new RuntimeException('cURL 錯誤:' . curl_error($ch));
}
curl_close($ch);
$json = json_decode($body, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException('JSON 解析失敗:' . json_last_error_msg());
}
// 回應結構:$json['responseData']['results'][...]
return $json['responseData']['results'] ?? [];
}
// --- 使用範例 ---
try {
$results = googleSearch('Paris Hilton', 'https://www.mywebsite.com');
foreach ($results as $r) {
echo "標題:{$r['title']}\n";
echo "網址:{$r['url']}\n";
echo "摘要:{$r['content']}\n---\n";
}
} catch (Throwable $e) {
error_log($e->getMessage());
}
?>
{
"responseData": {
"results": [
{
"url": "https://...",
"title": "Paris Hilton - Wikipedia",
"content": "Paris Whitney Hilton (born February 17, 1981)...",
"visibleUrl": "en.wikipedia.org",
"cacheUrl": "https://..."
},
...
],
"cursor": {
"estimatedResultCount": "12300000",
"currentPageIndex": 0,
"moreResultsUrl": "https://..."
}
},
"responseDetails": null,
"responseStatus": 200
}
cx (Search Engine ID)。https://www.googleapis.com/customsearch/v1?key=YOUR_KEY&cx=YOUR_CX&q=KEYWORDfunction customSearch(string $query, string $apiKey, string $cx): array
{
$url = 'https://www.googleapis.com/customsearch/v1?' . http_build_query([
'key' => $apiKey,
'cx' => $cx,
'q' => $query,
'num' => 10, // 每頁最多 10 筆
]);
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_TIMEOUT => 10,
]);
$body = curl_exec($ch);
curl_close($ch);
$data = json_decode($body, true);
return $data['items'] ?? [];
}
Referer,未設定會回傳 403。urlencode(),避免中文或特殊字元導致錯誤。curl.cainfo)。