萬盛學電腦網

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

PHP 遍歷 XML 文檔所有節點:DOMDocument + XPath 現代化實作

XML 雖非主流,但在金融匯率、電子發票、第三方對接、Sitemap、RSS 等場景仍廣泛使用。PHP 核心提供 **DOMDocument**(樹狀結構)與 **DOMXPath**(查詢語言),功能強大、標準相容、記憶體效率優於 SimpleXML。本文示範完整遍歷、查詢、修改、命名空間處理等實戰技巧。

載入 XML 的三種方式

<?php
$xmlString = file_get_contents('data.xml'); // 或 API 回應

// 1. DOMDocument(完整控制)
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false; // 忽略格式化空白
$dom->formatOutput = true;        // 輸出時縮排
$dom->loadXML($xmlString);        // 從字串
// $dom->load('data.xml');         // 從檔案

// 2. SimpleXML(簡單唯讀,記憶體較大)
$simplexml = simplexml_load_string($xmlString);

// 3. XMLReader(串流、超大檔、單向唯讀)
$reader = new XMLReader();
$reader->open('huge.xml');
?>

完整遍歷所有節點(遞迴)

<?php
function walkDomNode(DOMNode $node, int $depth = 0): void
{
    $indent = str_repeat('  ', $depth);

    switch ($node->nodeType) {
        case XML_ELEMENT_NODE:
            echo "{$indent}Element: {$node->nodeName}";
            if ($node->hasAttributes()) {
                echo " [";
                foreach ($node->attributes as $attr) {
                    echo " {$attr->name}=\"{$attr->value}\"";
                }
                echo " ]";
            }
            echo "\n";
            break;
        case XML_TEXT_NODE:
            $text = trim($node->textContent);
            if ($text !== '') {
                echo "{$indent}#text: " . htmlspecialchars($text) . "\n";
            }
            break;
        case XML_CDATA_SECTION_NODE:
            echo "{$indent}#cdata: " . htmlspecialchars($node->textContent) . "\n";
            break;
        case XML_COMMENT_NODE:
            echo "{$indent}#comment: " . htmlspecialchars($node->textContent) . "\n";
            break;
    }

    // 遞迴子節點
    if ($node->hasChildNodes()) {
        foreach ($node->childNodes as $child) {
            walkDomNode($child, $depth + 1);
        }
    }
}

// 使用
walkDomNode($dom->documentElement);
?>

XPath 查詢:精準定位節點

<?php
$xpath = new DOMXPath($dom);

// 1. 所有 contact 節點
$contacts = $xpath->query('//contact');

// 2. 特定屬性
$contact43956 = $xpath->query('//contact[@id="43956"]')->item(0);

// 3. 後代元素
$names = $xpath->query('//contact//name/first');

// 4. 條件過濾
$managers = $xpath->query('//contact[personal/title="Manager"]');

// 5. 命名空間處理(關鍵!)
$xmlNs = <<

  Value

XML;
$dom2 = new DOMDocument();
$dom2->loadXML($xmlNs);
$xpath2 = new DOMXPath($dom2);
$xpath2->registerNamespace('ns', 'https://example.com/ns');
$items = $xpath2->query('//ns:item'); // 必須註冊前綴
?>

修改 XML:新增、更新、刪除節點

<?php
// 新增子節點
$contact = $xpath->query('//contact[@id="43956"]')->item(0);
$personal = $xpath->query('personal', $contact)->item(0);

$work = $dom->createElement('work', '6666');
$personal->appendChild($work);

// 新增屬性
$work->setAttribute('type', 'phone');

// 插入到特定位置(第一個子節點前)
$firstChild = $personal->firstChild;
$personal->insertBefore($work, $firstChild);

// 更新文字內容
$title = $xpath->query('personal/title', $contact)->item(0);
$title->textContent = 'Senior Manager';

// 刪除節點
$dob = $xpath->query('personal/dob', $contact)->item(0);
$dob->parentNode->removeChild($dob);

// 輸出結果
echo $dom->saveXML();
?>

建立新 XML 文檔

<?php
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;

$root = $dom->createElement('contacts');
$dom->appendChild($root);

$contact = $dom->createElement('contact');
$contact->setAttribute('id', '99999');
$root->appendChild($contact);

$personal = $dom->createElement('personal');
$contact->appendChild($personal);

$name = $dom->createElement('name');
$personal->appendChild($name);

$first = $dom->createElement('first', 'John');
$name->appendChild($first);
// ... middle, last

$title = $dom->createElement('title', 'Engineer');
$personal->appendChild($title);

// 輸出
header('Content-Type: application/xml; charset=utf-8');
echo $dom->saveXML();
?>

大檔案處理:XMLReader(串流、低記憶體)

<?php
$reader = new XMLReader();
$reader->open('huge.xml');

while ($reader->read()) {
    if ($reader->nodeType === XMLReader::ELEMENT && $reader->localName === 'contact') {
        // 擴展為 DOM 節點處理
        $node = $reader->expand(); // 返回 DOMNode
        $dom = new DOMDocument();
        $imported = $dom->importNode($node, true);
        $dom->appendChild($imported);

        // 現在可用 XPath/DOM 操作這個 contact
        $xpath = new DOMXPath($dom);
        $id = $xpath->evaluate('string(@id)', $imported);
        $name = $xpath->evaluate('string(personal/name/first)', $imported);
        echo "Contact $id: $name\n";

        // 釋放記憶體
        $node = null;
        $dom = null;
    }
}
$reader->close();
?>

常見編碼坑點

  • UTF-8 必須宣告:``,且 PHP 檔案儲存為 UTF-8 無 BOM。
  • loadXML() 預期 UTF-8:若來源為 Big5/GBK,先 `iconv()` 或 `mb_convert_encoding()` 轉碼。
  • 實體參考:`&` `<` `>` `"` `'` 合法;其他數字實體 `〹` 合法;未定義實體會報錯,需 `libxml_use_internal_errors(true)` 抑制並處理。

效能比較(10MB XML,10萬節點)

方法記憶體峰值耗時適用場景
DOMDocument~180 MB1.2s需修改、XPath 複雜查詢、中小檔
SimpleXML~220 MB0.9s唯讀、簡單遍歷、中小檔
XMLReader~4 MB1.5s超大檔、單向處理、記憶體受限

選對工具,XML 處理不再是噩夢。DOMDocument + XPath 是功能最完整的標準組合;XMLReader 是大檔救星;SimpleXML 適合快速原型。

copyright © 萬盛學電腦網 all rights reserved