Google Custom Search JSON API 允許程式化搜尋網頁。本文說明如何使用 PHP cURL 呼叫 API、處理回應、避免常見錯誤。
cx (搜尋引擎 ID)<?php
class GoogleCustomSearch
{
private $apiKey;
private $cx;
private $baseUrl = 'https://www.googleapis.com/customsearch/v1';
public function __construct(string $apiKey, string $cx)
{
$this->apiKey = $apiKey;
$this->cx = $cx;
}
public function search(string $query, array $options = []): array
{
$params = [
'key' => $this->apiKey,
'cx' => $this->cx,
'q' => $query,
'num' => $options['num'] ?? 10, // 1-10
'start' => $options['start'] ?? 1, // 1-based, max 91
'lr' => $options['lr'] ?? '', // 語言限制,如 lang_zh-TW
'safe' => $options['safe'] ?? 'active', // off/medium/active
'dateRestrict' => $options['dateRestrict'] ?? '', // d[number], w[number], m[number], y[number]
'siteSearch' => $options['siteSearch'] ?? '', // 限定網站
'siteSearchFilter' => $options['siteSearchFilter'] ?? '', // i(包含)/e(排除)
];
$url = $this->baseUrl . '?' . http_build_query($params);
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15,
CURLOPT_CONNECTTIMEOUT => 5,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; PHP GoogleSearch/1.0)',
CURLOPT_HTTPHEADER => [
'Referer: https://your-domain.com', // 建議設定 Referer
],
]);
$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($errno) {
throw new RuntimeException("cURL 錯誤 ($errno): $error");
}
if ($httpCode !== 200) {
throw new RuntimeException("HTTP $httpCode: $response");
}
$data = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException('JSON 解析失敗: ' . json_last_error_msg());
}
// 檢查 API 錯誤
if (isset($data['error'])) {
throw new RuntimeException("API 錯誤: {$data['error']['message']} (代碼: {$data['error']['code']})");
}
return $data;
}
}
// 使用範例
$apiKey = 'YOUR_API_KEY';
$cx = 'YOUR_SEARCH_ENGINE_ID';
$search = new GoogleCustomSearch($apiKey, $cx);
try {
$result = $search->search('PHP 教學', [
'num' => 5,
'lr' => 'lang_zh-TW',
'dateRestrict' => 'm1', // 過去一個月
]);
foreach ($result['items'] ?? [] as $item) {
echo "<h3><a href='{$item['link']}' target='_blank'>{$item['title']}</a></h3>";
echo "<p>{$item['snippet']}</p>";
echo "<hr>";
}
// 分頁資訊
if (isset($result['queries']['nextPage'])) {
echo "總結果數: {$result['searchInformation']['totalResults']}";
}
} catch (Exception $e) {
echo '錯誤: ' . $e->getMessage();
}
?>
{
"kind": "customsearch#search",
"queries": {
"request": [...],
"nextPage": [...] // 有下一頁時存在
},
"searchInformation": {
"searchTime": 0.123,
"formattedSearchTime": "0.12",
"totalResults": "1230000",
"formattedTotalResults": "1,230,000"
},
"items": [
{
"kind": "customsearch#result",
"title": "頁面標題",
"htmlTitle": "頁面標題 (含粗體標記)",
"link": "https://example.com/page",
"displayLink": "example.com",
"snippet": "摘要文字...",
"htmlSnippet": "摘要文字 (含粗體標記)...",
"cacheId": "cached_page_id",
"formattedUrl": "https://example.com/page",
"htmlFormattedUrl": "https://example.com/page",
"pagemap": { ... } // 結構化資料
}
]
}
start 參數 (1, 11, 21... 最大 91),配合 nextPage 判斷是否還有下一頁。siteSearch: 'example.com' + siteSearchFilter: 'i'。-keyword。filetype:pdf。| HTTP 代碼 | 錯誤原因 | 處理 |
|---|---|---|
| 400 | 參數錯誤 (q 為空、cx 無效等) | 檢查請求參數 |
| 403 | API Key 無效、額度用盡、未啟用 API | 檢查 Cloud Console 設定 |
| 429 | 超過速率限制 (QPS/每日配額) | 指數退避重試、快取結果 |
| 500/503 | Google 伺服器內部錯誤 | 重試 |
Google Custom Search API 提供強大的網頁搜尋能力,PHP 串接簡單。注意免費額度限制 (100/天),生產環境務必實作快取與錯誤重試機制。