首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 呼叫 Google Search API (AJAX Search) 完整範例與 JSON 處理

     編輯:PHP 綜合知識

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
}

遷移至 Custom Search JSON API(現代做法)

  1. 至 Google Cloud Console 建立專案並啟用 Custom Search API。
  2. 建立 Programmable Search Engine 取得 cx (Search Engine ID)。
  3. 產生 API Key(建議限制 HTTP Referer 與 API 限制)。
  4. 請求網址:https://www.googleapis.com/customsearch/v1?key=YOUR_KEY&cx=YOUR_CX&q=KEYWORD
function 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 必填:舊版 AJAX Search API 強制檢查 Referer,未設定會回傳 403。
  • 配額限制:Custom Search API 免費方案每日 100 次查詢,超額需付費。
  • 編碼處理:關鍵字務必 urlencode(),避免中文或特殊字元導致錯誤。
  • HTTPS:新版 API 僅支援 HTTPS,請確保伺服器 CA 憑證最新(curl.cainfo)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved