利用 Google 搜尋 site:domain.com 語法,解析回傳 HTML 中 #resultStats 區塊的數字,估算網站收錄頁面數。注意:頻繁請求可能觸發 Google 反爬蟲機制(驗證碼、IP 封鎖),生產環境建議使用官方 Search Console API。
<?php
function getGoogleIndexCount($domain) {
$url = 'https://www.google.com/search?q=site:' . urlencode($domain);
$opts = [
'http' => [
'method' => 'GET',
'header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\r\n",
'timeout' => 10,
]
];
$context = stream_context_create($opts);
$html = @file_get_contents($url, false, $context);
if ($html === false) {
return 'Request failed';
}
// 解析結果統計區塊,正則需隨 Google 頁面結構調整
if (preg_match('/id=["\']resultStats["\'][^>]*>(.*?)<\/div>/is', $html, $matches)) {
$text = strip_tags($matches[1]);
// 提取數字(可能包含逗號、空格、中文「約」等)
if (preg_match('/([\d,\.]+)/', $text, $numMatch)) {
return (int)str_replace(',', '', $numMatch[1]);
}
}
return 'Parse failed';
}
// 使用
echo 'example.com 收錄量: ' . getGoogleIndexCount('example.com');
?>