萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 呼叫 Google Custom Search API 實作指南

前言

Google Custom Search JSON API 允許程式化搜尋網頁。本文說明如何使用 PHP cURL 呼叫 API、處理回應、避免常見錯誤。

前置準備

  1. Google Cloud Console 建立專案
  2. 啟用 Custom Search API
  3. 建立 API 金鑰 (API Key)
  4. 建立 可程式化搜尋引擎 (Programmable Search Engine) 取得 cx (搜尋引擎 ID)
  5. 免費額度:每日 100 次查詢

完整 PHP 實作

<?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。
  • 快取結果:搜尋結果變動較緩,建議快取 1-24 小時減少 API 呼叫。

錯誤代碼對照

HTTP 代碼錯誤原因處理
400參數錯誤 (q 為空、cx 無效等)檢查請求參數
403API Key 無效、額度用盡、未啟用 API檢查 Cloud Console 設定
429超過速率限制 (QPS/每日配額)指數退避重試、快取結果
500/503Google 伺服器內部錯誤重試

總結

Google Custom Search API 提供強大的網頁搜尋能力,PHP 串接簡單。注意免費額度限制 (100/天),生產環境務必實作快取與錯誤重試機制。

copyright © 萬盛學電腦網 all rights reserved