百度提供熱搜榜的 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 "獲取失敗,請檢查網路或介面變更。";
}
?>
https://top.baidu.com/rss_xml.php?p=top10 返回前 10 名熱搜的 XML 表格結構。simplexml_load_string 會自動依宣告轉碼。&,補上 & 避免解析錯誤。//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) |
https://api.oioweb.cn/api/baiduHot 等公開 API (穩定性無保證)。https://top.baidu.com/board?tab=realtime 頁面解析 (結構較穩定)。