提供兩項核心功能:抓取百度相關搜尋建議、計算內容原創度指標。適用於 SEO 優化、內容採集系統、關鍵字擴展等場景。
<?php
class BaiduSeo {
/**
* 建構搜尋請求 URI
* @param string $words 關鍵字
* @return string 完整查詢字串
*/
public static function buildRequestUri($words) {
$words = urlencode(Text::convertEncoding($words, 'GBK', 'UTF-8'));
return '/s?wd=' . $words;
}
/**
* 取得相關搜尋關鍵字
* @param string $words 查詢關鍵字
* @return array|false 相關搜尋陣列或失敗
*/
public static function getRelateSearch($words) {
$content = self::getContent($words);
// 解析相關搜尋區塊
if (preg_match('/<div id="rs">(((?!<\/div>).)*)<\/div>/s', $content, $result)) {
if (preg_match_all('/<a((?!>).)*>(.*?)<\/a>/s', $result[1], $matches)) {
return $matches[2];
}
}
return false;
}
/**
* 計算原創度指標(em 標籤出現次數)
* 數值越高表示文字長度越長且越不原創
* @param string $words 以空格分隔的關鍵字
* @return int 原創度分數
*/
public static function getEmTimes($words) {
$wordList = explode(' ', $words);
$content = self::getContent($words);
// 擷取所有 <em> 標籤內容
preg_match_all('/<em>(((?!<\/em>).)*)<\/em>/s', $content, $result);
if (!isset($result[1]) || count($result[1]) === 0) {
return 0;
}
$wordTable = array_count_values($result[1]);
$times = 0;
foreach ($wordList as $piece) {
if (array_key_exists($piece, $wordTable)) {
$times += $wordTable[$piece];
}
}
return $times;
}
/**
* 取得搜尋頁面內容(含快取機制)
* @param string $words 關鍵字
* @return string HTML 內容
*/
public static function getContent($words) {
static $loadedContents = [];
if (!isset($loadedContents[$words])) {
$url = 'https://www.baidu.com' . self::buildRequestUri($words);
$content = file_get_contents($url);
$content = Text::convertEncoding($content, 'UTF-8', 'GBK');
$loadedContents[$words] = $content;
}
return $loadedContents[$words];
}
/**
* 檢查是否觸發百度驗證碼
* @param string $content 頁面內容
* @return void
*/
public static function checkVerify($content) {
if (strpos($content, 'https://verify.baidu.com/') !== false) {
// 觸發驗證,需處理異常情況
throw new Exception('百度要求驗證碼,請降低請求頻率或使用代理');
}
}
}
<?php
require_once 'BaiduSeo.php';
$keywords = 'PHP 框架 推薦';
try {
// 取得相關搜尋
$related = BaiduSeo::getRelateSearch($keywords);
echo "相關搜尋:\n";
print_r($related);
// 計算原創度
$emTimes = BaiduSeo::getEmTimes($keywords);
echo "原創度指標 (em_times):$emTimes\n";
// 指標解讀
if ($emTimes > 50) {
echo "⚠️ 內容可能重複度較高,建議重寫\n";
} elseif ($emTimes > 20) {
echo "⚡ 內容有一定重複,可適度修改\n";
} else {
echo "✅ 內容原創度較好\n";
}
} catch (Exception $e) {
echo "錯誤:" . $e->getMessage();
}
百度搜尋頁面使用 GBK 編碼,PHP 內部建議統一 UTF-8,需雙向轉換。`Text::convertEncoding()` 為自訂工具類,可用 `mb_convert_encoding()` 或 `iconv()` 替代。
靜態變數 `$loadedContents` 避免同一關鍵字重複請求,減少頻寬與被封風險。
大量抓取搜尋引擎資料可能違反服務條款。建議: