萬盛學電腦網

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

Simple HTML DOM Parser 使用指南:以 jQuery 風格解析 HTML

簡介

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);
?>

核心方法:find() 選擇器

<?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'

DOM 遍歷方法

<?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;
?>

修改 DOM 並輸出

<?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
World
?>

記憶體管理

<?php
$dom->clear(); // 釋放循環引用記憶體,大量解析時建議每輪呼叫
unset($dom);
?>

效能與替代方案

  • 大型文件 (>1MB) 解析較慢、記憶體高,建議改用 DOMDocument + DOMXPath (原生 C 擴展) 或 Masterminds/HTML5 (HTML5 標準解析器)。
  • Simple HTML DOM 適合中小型頁面、快速原型、熟悉 jQuery 風格的開發者。
copyright © 萬盛學電腦網 all rights reserved