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

PHP file_get_contents 獲取百度熱搜關鍵字簡易實作

     編輯:PHP 相關知識

PHP 讀取百度熱搜榜 RSS 並解析關鍵字

百度提供熱搜榜的 RSS/XML 介面,透過 file_get_contents 即可快速獲取並解析。本文提供精簡、可直接使用的函式,適合整合至側邊欄、關鍵字推薦或 SEO 分析工具。

核心函式

<?php
/**
 * 獲取百度熱搜關鍵字
 * @return array 關鍵字陣列,失敗返回空陣列
 */
function getBaiduHotKeywords() {
    $url = 'https://top.baidu.com/rss_xml.php?p=top10';
    $content = @file_get_contents($url);
    if ($content === false) return [];
    
    // 百度 RSS 為 GBK 編碼,且包含 HTML 實體,需預處理
    if (preg_match('/<table>(.*)<\/table>/is', $content, $m)) {
        $content = $m[0];
        $content = str_replace('&', '&', $content); // 修正實體
    }
    // 補上 XML 宣告指定編碼
    $content = '' . $content;
    
    $xml = simplexml_load_string($content);
    if (!$xml) return [];
    
    $keywords = [];
    // 遍歷表格列 (結構可能隨百度更新而變)
    foreach ($xml->xpath('//tr') as $row) {
        $a = $row->xpath('td/a');
        if ($a) {
            $keywords[] = trim((string)$a[0]);
        }
    }
    return $keywords;
}

// 使用範例
$hotWords = getBaiduHotKeywords();
if ($hotWords) {
    echo "<ul>";
    foreach ($hotWords as $kw) {
        echo "<li><a href='https://www.baidu.com/s?wd=" . urlencode($kw) . "' target='_blank'>" . htmlspecialchars($kw) . "</a></li>";
    }
    echo "</ul>";
} else {
    echo "獲取失敗,請檢查網路或介面變更。";
}
?>

程式碼解析

  1. 資料來源:https://top.baidu.com/rss_xml.php?p=top10 返回前 10 名熱搜的 XML 表格結構。
  2. 編碼處理:XML 宣告為 GBK,PHP 預設 UTF-8,simplexml_load_string 會自動依宣告轉碼。
  3. 實體修正:原始 XML 可能包含未轉義的 &,補上 &amp; 避免解析錯誤。
  4. XPath 解析:使用 //tr/td/a 定位關鍵字連結,具備一定容錯性。

進階:加入快取機制 (檔案快取)

<?php
function getBaiduHotKeywordsCached($ttl = 3600) {
    $cacheFile = sys_get_temp_dir() . '/baidu_hot_keywords.json';
    
    // 讀取快取
    if (file_exists($cacheFile) && (time() - filemtime($cacheFile) < $ttl)) {
        return json_decode(file_get_contents($cacheFile), true);
    }
    
    // 獲取新資料
    $keywords = getBaiduHotKeywords();
    if ($keywords) {
        file_put_contents($cacheFile, json_encode($keywords));
    }
    return $keywords;
}
?>

常見問題排查

現象可能原因解決方案
返回空陣列allow_url_fopen=Off改用 cURL 版 fetchUrl() (見上一篇文章)
simplexml_load_string 警告XML 格式錯誤/編碼不符檢查 preg_match 擷取範圍、確認 encoding="GBK"
關鍵字為空百度頁面結構變更輸出 $content 分析新結構,調整 XPath
中文亂碼PHP 腳本非 UTF-8確保檔案儲存為 UTF-8 無 BOM,或 iconv('GBK','UTF-8',$kw)

替代資料來源

  • 百度開放平台:官方 API (需申請)。
  • 第三方聚合:如 https://api.oioweb.cn/api/baiduHot 等公開 API (穩定性無保證)。
  • 自建爬蟲:定時抓取 https://top.baidu.com/board?tab=realtime 頁面解析 (結構較穩定)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved