透過模擬百度搜尋請求 (site:domain.com),解析回傳 HTML 頁面中的收錄數量統計與列表連結。注意:百度反爬機制嚴格,生產環境建議使用官方 API (百度站長平台/搜尋資源平台)。
function baiduIndexCheck($domain, $page = 1) {
// 百度 site 語法查詢
$url = "https://www.baidu.com/s?wd=site:" . urlencode($domain) . "&pn=" . (($page - 1) * 10);
$headers = [
'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language: zh-CN,zh;q=0.9',
'Referer: https://www.baidu.com/',
];
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_TIMEOUT => 15,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSL_VERIFYPEER => false,
]);
$html = curl_exec($ch);
curl_close($ch);
if (!$html) return ['count' => 0, 'list' => []];
// 解析收錄數量 (百度頁面結構常變,需定期維護選擇器)
$count = 0;
if (preg_match('/找到相關結果數約?([\d,]+)<\/span>/i', $html, $m)) {
$count = (int)str_replace(',', '', $m[1]);
} elseif (preg_match('/百度為您找到相關結果約?([\d,]+)個/i', $html, $m)) {
$count = (int)str_replace(',', '', $m[1]);
}
// 解析列表連結
$list = [];
$dom = new DOMDocument();
@$dom->loadHTML('' . $html); // 抑制 HTML5 錯誤
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//div[contains(@class, "result")]//h3/a');
foreach ($nodes as $node) {
$list[] = [
'title' => trim($node->textContent),
'url' => $node->getAttribute('href'),
];
}
return ['count' => $count, 'list' => $list];
}
// 使用
$result = baiduIndexCheck('example.com');
echo "收錄約 {$result['count']} 頁\n";
foreach ($result['list'] as $item) {
echo "- {$item['title']}: {$item['url']}\n";
}
Content-Type 或 <meta charset> 動態處理pn 參數控制,每頁 10 筆
// 百度站長平台 API (需驗證站點擁有權)
$apiUrl = "https://api.baidu.com/json/tongji/v1/ReportService/getData";
$params = [
'access_token' => $token,
'site_id' => $siteId,
'method' => 'overview/getSummary',
'start_date' => date('Y-m-d', strtotime('-30 days')),
'end_date' => date('Y-m-d'),
'metrics' => 'pv_count,visitor_count',
];
// 回傳結構化 JSON,無需解析 HTML