抓取網頁所有 `` 連結是爬蟲、SEO 分析、死連結檢測的基礎需求。PHP 內建 DOMDocument + DOMXPath 提供標準、健壯的 HTML 解析能力,避免正則表達式處理不完整/巢狀標籤的風險。
<?php
$url = 'https://www.example.com';
// 1. 取得 HTML 內容(生產環境建議用 cURL 處理重導向、逾時、Cookie)
$html = file_get_contents($url);
if ($html === false) {
die("無法取得頁面內容");
}
// 2. 建立 DOMDocument 並載入 HTML
$dom = new DOMDocument();
// 抑制不符標準 HTML 產生的警告
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_clear_errors();
// 3. 建立 XPath 查詢所有 元素
$xpath = new DOMXPath($dom);
$links = $xpath->query('//a[@href]'); // 只選擇有 href 屬性的 a 標籤
// 4. 遍歷輸出
foreach ($links as $link) {
$href = $link->getAttribute('href');
$text = trim($link->nodeValue);
echo "URL: {$href} | 文字: {$text}\n";
}
| 需求 | XPath 表達式 |
|---|---|
| 所有連結(含無 href) | //a |
| 僅外部連結 | //a[starts-with(@href, 'http')] |
| 特定 class 的連結 | //a[contains(@class, 'btn')] |
| 排除錨點連結 | //a[@href and not(starts-with(@href, '#'))] |
/path 或 ../page,需用 parse_url + 基礎 URL 組合成絕對路徑。loadHTML 預期 UTF-8,若來源為 Big5/GBK,需先 mb_convert_encoding($html, 'HTML-ENTITIES', '原編碼')。XMLReader 流式解析。function getAbsoluteLinks(string $url): array
{
$html = @file_get_contents($url);
if (!$html) return [];
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_clear_errors();
$xpath = new DOMXPath($dom);
$anchors = $xpath->query('//a[@href]');
$base = parse_url($url, PHP_URL_SCHEME) . '://' . parse_url($url, PHP_URL_HOST);
$results = [];
foreach ($anchors as $a) {
$href = $a->getAttribute('href');
// 簡易相對轉絕對
if (strpos($href, 'http') !== 0) {
$href = $base . ($href[0] === '/' ? '' : '/') . $href;
}
$results[] = [
'url' => $href,
'text' => trim($a->nodeValue),
];
}
return $results;
}
// 使用
$links = getAbsoluteLinks('https://www.example.com');
print_r($links);