Simple HTML DOM Parser 是一個純 PHP 實現的 HTML 解析器(PHP 5.3+),支持:
項目地址:github.com/samacs/simple_html_dom
composer require sunra/php-simple-html-dom-parsersimple_html_dom.php 放入項目 include。require_once 'simple_html_dom.php';
$html = new simple_html_dom();
// 1. 從 URL 加載(內部用 file_get_contents,建議改用 cURL 獲取後用 load())
$html->load_file('https://www.example.com');
// 2. 從字符串加載(推薦:先用 cURL 獲取內容)
$html->load('從字符串加載');
// 3. 從本地文件加載
$html->load_file('/path/to/file.html');
find() 選擇器大全返回 元素對象數組,或指定索引返回單個對象(未找到返回 null)。
| 選擇器 | 說明 | 示例 |
|---|---|---|
| 標籤名 | 所有該標籤 | $html->find('a') |
| ID 選擇器 | 唯一元素 | $html->find('#container') 或 $html->find('div[id=main]', 0) |
| Class 選擇器 | 所有該類 | $html->find('.foo') |
| 屬性存在 | 包含該屬性 | $html->find('[id]')、$html->find('div[id]') |
| 屬性等值 | 精確匹配 | $html->find('a[href="https://example.com"]') |
| 屬性開頭/結尾/包含 | 正則風格 | [href^="https"]、[src$=".jpg"]、[class*="btn-"] |
| 多選擇器 | 並集 | $html->find('a, img, script') |
| 後代組合 | 空格分隔 | $html->find('ul li')、$html->find('ul li.selected') |
$e = $html->find('#main', 0);
$e->parent; // 父元素
$e->children; // 子元素數組
$e->children(0); // 第一個子元素
$e->first_child(); // 同上
$e->last_child(); // 最後一個子元素
$e->prev_sibling(); // 上一個同級元素
$e->next_sibling(); // 下一個同級元素
| 屬性 | 含義 | 等價 jQuery |
|---|---|---|
tag | 標籤名(小寫) | prop('tagName').toLowerCase() |
innertext | 內部 HTML | html() |
outertext | 包含自身的 HTML | prop('outerHTML') |
plaintext | 純文本(去除標籤) | text() |
$a = $html->find('a', 0);
// 讀取
$href = $a->href;
// 修改
$a->href = 'https://new-url.com';
$a->class = 'btn btn-primary';
$a->{'data-id'} = 123; // 包含特殊字符的屬性用大括號
// 刪除
$a->href = null;
unset($a->href); // 同效
// 判斷存在
if (isset($a->href)) { ... }
$e = $html->find('.target', 0);
// 1. 刪除元素
$e->outertext = '';
// 2. 替換元素
$e->outertext = '新內容';
// 3. 包裹元素
$e->outertext = '' . $e->outertext . '';
// 4. 前插入
$e->outertext = '前置' . $e->outertext;
// 5. 後插入
$e->outertext = $e->outertext . '後置';
// 直接輸出整個文檔
echo $html;
// 或獲取字符串
$doc = (string)$html; // 或 $html->save()
file_put_contents('modified.html', $doc);
Simple HTML DOM 內部構建大量對象引用循環,**PHP 垃圾回收器(GC)無法自動回收**,大量解析會導致內存耗盡。
務必在用完後調用:
$html->clear(); // 斷開引用循環,釋放內存
unset($html); // 可選
最佳實踐: 封裝為服務類,單次請求解析多頁時,**每頁解析完立即 clear()**,或使用生成器逐頁處理。
| 方案 | 優點 | 缺點 | 推薦場景 |
|---|---|---|---|
| Simple HTML DOM | API 簡單、jQuery 風格、容錯強 | 純 PHP 慢、內存洩漏需手動清理、無 XPath | 簡單腳本、兼容舊代碼、小規模解析 |
| DOMDocument + DOMXPath | 內建、標準、支持 XPath、性能好 | 嚴格模式難解析髒 HTML、API 繁瑣 | 結構良好 XML/HTML、需 XPath 查詢 |
| Masterminds/HTML5 (PHP) | HTML5 標準解析器、極強容錯 | 較慢、較新 | 現代項目、需標準合規解析 |
| symfony/dom-crawler | jQuery API、CSS 選擇器、集成 Symfony | 需 Composer、較重 | Symfony/Laravel 項目、測試爬蟲 |