功能一:百度收錄量查詢
<?php
function baiduIndexCount($domain) {
$url = "https://www.baidu.com/s?wd=site%3A" . urlencode($domain);
$html = file_get_contents($url);
// $html = iconv("gb2312", "UTF-8", $html); // 視頁面編碼決定
if (preg_match('/找到相關結果數約?([\d,]+)個/', $html, $m)) {
return (int)str_replace(',', '', $m[1]);
}
return 0;
}
echo baiduIndexCount('jb51.net');
功能二:百度熱搜詞(RSS 接口)
<?php
function getBaiduHotKeywords() {
$rss = file_get_contents('https://top.baidu.com/rss_xml.php?p=top10');
if (preg_match('/(.*)<\/table>/is', $rss, $m)) {
$table = str_replace('&', '&', $m[0]);
$xml = simplexml_load_string('' . $table);
$keywords = [];
foreach ($xml->tbody->tr as $tr) {
if (!empty($tr->td->a)) $keywords[] = trim((string)$tr->td->a);
}
return $keywords;
}
return [];
}
print_r(getBaiduHotKeywords());
功能三:百度收錄 + 快照時間(綜合頁面)
<?php
$domain = "https://www.jb51.net/";
$site_url = 'https://www.baidu.com/s?wd=site%3A';
$all = $site_url . urlencode($domain);
$today = $all . '&lm=1'; // 今日收錄(可能已失效)
$utf_pat = '/找到相關結果數約?([\d,]+)個/';
$snap_pat = '/([^<]*)<\/span>/';
$date_pat = '/\d{4}-\d{1,2}-\d{1,2}/';
$s0 = @file_get_contents($all);
$s1 = @file_get_contents($today);
preg_match($utf_pat, $s0, $all_num);
preg_match($utf_pat, $s1, $today_num);
preg_match($snap_pat, $s0, $tmp);
preg_match($date_pat, $tmp[0] ?? '', $snap);
$all_num = $all_num[1] ?? 0;
$today_num = $today_num[1] ?? 0;
$snap = $snap[0] ?? '暫無快照';
?>
<html><body>
<table border="1">
<tr><th>日期</th><th>百度收錄</th><th>今日收錄</th><th>快照日期</th></tr>
<tr>
<td><?= date('m月d日G時') ?></td>
<td><?= $all_num ?></td>
<td><?= $today_num ?></td>
<td><?= $snap ?></td>
</tr>
</table>
<p>收錄詳情:<a href="<?= $all ?>" target="_blank"><?= $all_num ?></a></p>
<p>快照詳情:<a href="<?= $all ?>" target="_blank"><?= $snap ?></a></p>
</body></html>
關鍵技術點
| 技術 | 說明 |
| User-Agent | 建議設置常見瀏覽器 UA,避免被反爬攔截 |
| 編碼處理 | 百度頁面多為 GBK,需 iconv('GBK','UTF-8',$html) 後再正則 |
| 正則穩健性 | 頁面結構常變,建議多模式匹配 + 異常兜底 |
| 請求頻率 | 單 IP 高頻會被封禁,生產環境必須加緩存 + 代理池 |
| 法律合規 | 僅供學習研究,商業用途請使用百度官方開放平台 API |
現代替代方案
- 百度站長平台:官方提供收錄、流量、關鍵詞 API,需驗證站點所有權
- 第三方 SEO 工具:5118、愛站、站長工具等提供 API 接口
- 自建爬蟲集群:Scrapy + Redis + Proxy Pool,定時抓取存入數據庫
直接抓取百度前端頁面屬於灰色地帶,穩定性差、法律風險高,強烈建議遷移至官方或授權數據源。
- 上一篇文章: PHP Socket 實現 HTTP GET/POST 請求底層通訊詳解
- 下一篇文章: PHP 獲取指定範圍隨機不重複數組的高效實現
Copyright ©
程式碼之家 All Rights Reserved