方法對比總覽
| 方法 | 適用場景 | 優點 | 缺點 | 依賴 |
| strip_tags() | 快速移除所有標籤、保留特定標籤 | 內建、極快、記憶體少 | 無法處理屬性、巢狀邏輯、破碎 HTML | 無 |
| strpos + substr | 固定結構、單一標籤提取 | 零依賴、可控 | 極其脆弱、維護困難 | 無 |
| DOMDocument | 標準化、結構化操作、XPath 查詢 | W3C 標準、支援 HTML5 (libxml)、健壯 | 效能較低、編碼處理麻煩 | PHP 核心 |
| Simple HTML DOM | 快速開發、jQuery 風格選擇器 | API 直覺、容錯強、支援 CSS 選擇器 | 純 PHP 實現較慢、大檔案記憶體大 | 第三方庫 |
1. strip_tags():最輕量的淨化
<?php
$html = '<div><p class="lead">Hello <b>World</b>!</p><script>alert(1)</script></div>';
// 移除所有標籤
echo strip_tags($html); // Hello World!
// 保留 <p> <b>
echo strip_tags($html, '<p><b>'); // <p class="lead">Hello <b>World</b>!</p>
// ⚠️ 屬性保留:strip_tags 不會移除屬性(如 class、onclick),XSS 風險!
// 生產環境必須搭配 HTMLPurifier 深度淨化
?>
2. DOMDocument:標準化結構操作
<?php
$html = '<ul><li id="a">Item A</li><li id="b">Item B</li></ul>';
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML('<meta charset="utf-8">' . $html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
libxml_clear_errors();
$xpath = new DOMXPath($dom);
// 查詢所有 li
foreach ($xpath->query('//li') as $li) {
echo "ID: {$li->getAttribute('id')}, Text: {$li->nodeValue}<br>";
}
// 修改內容
$firstLi = $xpath->query('//li[1]')->item(0);
$firstLi->nodeValue = 'Updated A';
$firstLi->setAttribute('class', 'active');
// 輸出
echo $dom->saveHTML();
?>
3. Simple HTML DOM:爬蟲首選
<?php
require_once 'simple_html_dom.php';
$html = file_get_html('https://example.com/articles');
// CSS 選擇器提取
foreach ($html->find('article h2 a') as $link) {
echo $link->href . ' - ' . $link->plaintext . '<br>';
}
// 修改 DOM
$html->find('div.content', 0)->innertext = '<p>New Content</p>';
echo $html->save();
// 記憶體釋放(重要!)
$html->clear();
unset($html);
?>
4. 正則表達式:特定模式提取(不推薦通用解析)
<?php
$html = '<img src="photo.jpg" alt="Photo"> <img src="pic.png" alt="Pic">';
// 僅提取 src
preg_match_all('/<img[^>]+src=["\']([^"\']+)["\']/i', $html, $matches);
print_r($matches[1]); // ['photo.jpg', 'pic.png']
// ⚠️ 正則無法正確處理巢狀、跨行、屬性順序變化,僅用於極簡單固定格式
?>
選型決策樹
- 只需純文字摘要 →
strip_tags() + mb_substr()
- 需提取特定屬性/結構、專案已用 Composer → Simple HTML DOM 或 symfony/dom-crawler
- 需嚴格標準合規、XPath 複雜查詢、無第三方依賴 → DOMDocument
- 超大檔案(>10MB)流式處理 →
XMLReader (SAX 模式)
安全提醒
- 任何來自用戶輸入的 HTML 輸出前,必須經過 HTMLPurifier 淨化
strip_tags() 保留標籤時會保留屬性(含 onclick、style),極高 XSS 風險
- 解析外部網頁時設定
libxml_disable_entity_loader(true) 防止 XXE 攻擊