Simple HTML DOM 是 PHP 純函式庫,支援 CSS 選擇器語法 (find()) 類似 jQuery,適合爬蟲、內容抓取、HTML 清洗。無需安裝擴展,單一 simple_html_dom.php 即可使用。
<?php
require_once 'simple_html_dom.php'; // 或 composer require sunra/php-simple-html-dom-parser
// 從 URL 載入
$html = file_get_html('https://example.com');
// 從字串載入
$html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');
// 或 new 物件後 load()
$dom = new simple_html_dom();
$dom->load($htmlString);
?>
<?php
$dom = file_get_html('https://example.com');
// 所有 標籤
foreach ($dom->find('a') as $a) {
echo $a->href . '<br>';
}
// 第 N 個元素 (0-based)
$firstDiv = $dom->find('div', 0);
$lastImg = $dom->find('img', -1); // 最後一個
// 屬性選擇器
$dom->find('div[id]'); // 有 id 的 div
$dom->find('div[id=foo]'); // id="foo"
$dom->find('#foo'); // id="foo" (同 CSS)
$dom->find('.foo'); // class="foo"
// 多選擇器
$dom->find('a, img'); // 所有 a 和 img
$dom->find('a[title], img[title]'); // 有 title 屬性的 a、img
// 後代選擇器
$dom->find('ul li'); // ul 下的 li
$dom->find('div div div'); // 三層 div
$dom->find('table.hello td'); // class=hello 的 table 下的 td
$dom->find('table td[align=center]'); // table 下 align=center 的 td
?>
| 屬性/方法 | 說明 | 範例 |
|---|---|---|
$e->tag | 標籤名 | 'div' |
$e->outertext | 包含自身的完整 HTML | '<div>foo</div>' |
$e->innertext | 內部 HTML (不含自身標籤) | 'foo <b>bar</b>' |
$e->plaintext | 純文字 (去除所有標籤) | 'foo bar' |
$e->attr['href'] | 屬性值 (陣列存取) | '/link' |
$e->href | 常用屬性可直接當屬性存取 | '/link' |
<?php
$e = $dom->find('div', 0);
$e->children(); // 所有子元素 (陣列)
$e->children(1); // 第 2 個子元素
$e->parent(); // 父元素
$e->first_child(); // 第一個子元素
$e->last_child(); // 最後一個子元素
$e->next_sibling(); // 下一個兄弟
$e->prev_sibling(); // 上一個兄弟
// 連續遍歷範例
echo $dom->find('#div1', 0)->children(1)->children(1)->children(2)->id;
?>
<?php
$html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');
$dom = new simple_html_dom();
$dom->load($html);
$dom->find('div', 1)->class = 'bar'; // 修改屬性
$dom->find('div[id=hello]', 0)->innertext = 'foo'; // 修改內容
echo $dom; // 輸出修改後的 HTML
// foo
?>
<?php
$dom->clear(); // 釋放循環引用記憶體,大量解析時建議每輪呼叫
unset($dom);
?>
DOMDocument + DOMXPath (原生 C 擴展) 或 Masterminds/HTML5 (HTML5 標準解析器)。