載入方式三選一
<?php
require 'simple_html_dom.php';
$dom = new simple_html_dom();
// 1. 從 URL 直接抓取
$dom->load_file('https://example.com');
// 2. 從字串載入
$dom->load($htmlString);
// 3. 靜態工廠方法(內部 new + load)
$dom = str_get_html($htmlString);
?>
選擇器 find() 全模式
| 呼叫方式 | 回傳 | 說明 |
find('selector') | 元素陣列 | 所有匹配 |
find('selector', 0) | 單一元素 / null | 第一個(索引 0) |
find('selector', -1) | 單一元素 / null | 最後一個 |
find('selector', n) | 單一元素 / null | 第 n 個(0-based) |
選擇器語法速查
$dom->find('a'); // 所有
$dom->find('a', 0); // 第一個
$dom->find('a', -1); // 最後一個
$dom->find('div[id]'); // 有 id 屬性的 div
$dom->find('div[id=foo]'); // id="foo" 的 div
$dom->find('#foo'); // id="foo" 任意元素
$dom->find('.foo'); // class="foo" 任意元素
$dom->find('*[id]'); // 有 id 屬性的任意元素
$dom->find('a, img'); // 所有 和
$dom->find('a[title], img[title]'); // 有 title 的 和
$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 = $dom->find('div', 0);
echo $e->tag; // "div"
echo $e->outertext; // "foo bar
"
echo $e->innertext; // "foo bar"
echo $e->plaintext; // "foo bar"
DOM 遍歷六大方法
| 方法 | 回傳 | 說明 |
children([$index]) | 陣列 / 元素 / null | 直接子元素 |
parent() | 元素 / null | 父元素 |
first_child() | 元素 / null | 第一個子元素 |
last_child() | 元素 / null | 最後一個子元素 |
next_sibling() | 元素 / null | 下一個兄弟 |
prev_sibling() | 元素 / null | 上一個兄弟 |
鏈式呼叫範例
// 取得 #div1 孫子的孫子的 id
echo $dom->find('#div1', 0)->children(1)->children(1)->children(2)->id;
// 等同 DOMDocument 風格
echo $dom->getElementById('div1')
->childNodes->item(1)
->childNodes->item(1)
->childNodes->item(2)
->getAttribute('id');
修改 DOM 並輸出
$dom = str_get_html('Hello
World
');
$dom->find('div', 1)->class = 'bar'; // 設定屬性
$dom->find('div[id=hello]', 0)->innertext = 'foo'; // 修改內容
echo $dom;
// 輸出: foo
World
核心方法表
| 方法 | 說明 |
__construct([$filename]) | 建構子,可選自動載入檔案/URL |
load($str) | 從字串載入 |
load_file($filename) | 從檔案/URL 載入 |
save([$filename]) | 輸出字串,若給檔名則存檔 |
set_callback($fn) | 設定回調函數(特定事件觸發) |
find($selector, [$index]) | 核心查找方法 |
clear() | 釋放循環引用記憶體 |
getElementById($id) | 依 id 取元素(較 find('#id') 快) |
記憶體管理最佳實踐
- 大文檔處理完畢立即
$dom->clear(); unset($dom);。
- 長時間爬蟲每 20-50 頁重建
$dom = new simple_html_dom(); 避免記憶體碎片。
- 若只需提取少數資料,考慮改用
DOMDocument + DOMXPath(C 底層,記憶體佔用更低)。