萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

Simple HTML DOM Parser 快速上手:find()、plaintext、innertext 核心用法

核心流程三步驟

  1. require_once 'simple_html_dom.php'
  2. $dom = new simple_html_dom(); $dom->load($html); 或 $dom = file_get_html($url);
  3. $dom->find('selector', $index) 取得元素,讀取 plaintext / innertext / outertext / attr[]。

常用選擇器速查

選擇器說明
div所有 div
div.lookLeftnameclass="lookLeftname" 的 div
div#mainid="main" 的 div
div[id]有 id 屬性的 div
a[target=_blank]target="_blank" 的 a
ul > liul 直系子元素 li
table tr tdtable 後代 td
img, a所有 img 和 a

元素屬性對照

<?php
$html = '<div id="hello">Hello <b>World</b></div>';
$dom = str_get_html($html);
$e = $dom->find('div', 0);

echo $e->tag;        // "div"
echo $e->outertext;  // '<div id="hello">Hello <b>World</b></div>'
echo $e->innertext;  // 'Hello <b>World</b>'
echo $e->plaintext;  // 'Hello World'
echo $e->id;         // 'hello' (常用屬性可直接存取)
echo $e->attr['id']; // 'hello' (通用屬性陣列)
?>

實戰範例:抓取文章標題、摘要、圖片

<?php
$dom = file_get_html('https://example.com/blog');

$articles = [];
foreach ($dom->find('article.post') as $post) {
    $item = [];
    $item['title'] = $post->find('h2.title', 0)->plaintext;
    $item['summary'] = $post->find('div.excerpt', 0)->plaintext;
    $imgEl = $post->find('img.cover', 0);
    $item['image'] = $imgEl ? $imgEl->src : '';
    $articles[] = $item;
}
print_r($articles);
$dom->clear(); // 釋放記憶體
?>

修改 DOM 並輸出

<?php
$dom = str_get_html('<div class="old">Content</div>');
$div = $dom->find('div', 0);
$div->class = 'new';
$div->innertext = 'Updated Content';
echo $dom; // <div class="new">Updated Content</div>
?>

遍歷關係

<?php
$e = $dom->find('#container', 0);
$e->children();        // 所有子節點
$e->children(0);       // 第一個子節點
$e->parent();          // 父節點
$e->first_child();     // 第一個子節點
$e->last_child();      // 最後一個子節點
$e->next_sibling();    // 下一個兄弟
$e->prev_sibling();    // 上一個兄弟
?>

注意事項

  • file_get_html() 內部使用 file_get_contents(),需開啟 allow_url_fopen 或改用 cURL 取得內容後 str_get_html()。
  • 大型文件 (>2MB) 解析慢、記憶體大,建議改用 DOMDocument + DOMXPath。
  • HTML5 標籤 (如 <main>, <article>) 支援度視版本而定,最新版已支援。
  • 記得 $dom->clear() 避免循環引用記憶體洩漏。
copyright © 萬盛學電腦網 all rights reserved