萬盛學電腦網

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

PHP 讀寫 XML 檔案完整教學:DOMDocument 實戰與最佳實踐

前言

XML 作為資料交換與配置儲存的經典格式,在 PHP 中主要透過 DOMDocument、SimpleXML、XMLReader/Writer 三大 API 處理。本文以 DOMDocument 為核心,示範從零建構、讀取、修改 XML 的完整流程,並對比各 API 適用場景。

一、快速上手:SimpleXML 輕量讀寫

適合結構簡單、無需複雜操作的場景:

<?php
header('Content-Type: text/html; charset=utf-8');

// 讀取
$xml = simplexml_load_file('example.xml');
echo $xml->article->title; // 直接屬性存取

// 修改
$xml->article->title = '新標題';

// 寫入
$xml->asXML('example_modified.xml');
?>

優點:語法直觀、代碼極少。
缺點:難以處理同名節點、命名空間、CDATA、註解、DTD 驗證等進階需求。

二、專業級:DOMDocument 完整範例

1. 建立 XML 文件

<?php
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true; // 格式化縮排

// 建立根節點
$root = $dom->createElement('articles');
$dom->appendChild($root);

// 批次新增文章(陣列資料來源)
$articles = [
  ['id' => '1', 'title' => 'PHP 入門', 'link' => 'https://example.com/1'],
  ['id' => '2', 'title' => 'PHP 進階', 'link' => 'https://example.com/2'],
];

foreach ($articles as $art) {
  $article = $dom->createElement('article');
  $article->setAttribute('id', $art['id']); // 設定屬性
  
  $title = $dom->createElement('title', $art['title']);
  $link  = $dom->createElement('link', $art['link']);
  
  $article->appendChild($title);
  $article->appendChild($link);
  $root->appendChild($article);
}

// 輸出或存檔
echo $dom->saveXML();        // 字串輸出
$dom->save('articles.xml');  // 存檔,返回位元組數
?>

2. 讀取與遍歷 XML

<?php
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->load('articles.xml');

$articles = $dom->getElementsByTagName('article');
echo "共 {$articles->length} 篇文章\n";

foreach ($articles as $article) {
  $id    = $article->getAttribute('id');
  $title = $article->getElementsByTagName('title')->item(0)->nodeValue;
  $link  = $article->getElementsByTagName('link')->item(0)->nodeValue;
  
  echo "[$id] $title -> $link\n";
}
?>

3. 進階操作:XPath 查詢、CDATA、命名空間

<?php
$dom = new DOMDocument();
$dom->load('complex.xml');

$xpath = new DOMXPath($dom);
// 註冊命名空間
$xpath->registerNamespace('ns', 'https://example.com/ns');

// 查詢:所有狀態為 published 的文章標題
$titles = $xpath->query('//ns:article[@status="published"]/ns:title');
foreach ($titles as $title) {
  echo $title->nodeValue . "\n";
}

// 建立 CDATA 區段
$desc = $dom->createElement('description');
$cdata = $dom->createCDATASection('內容包含 <特殊字符> & "引號"');
$desc->appendChild($cdata);
$article->appendChild($desc);
?>

三、大型 XML 處理:XMLReader (Pull Parser)

記憶體效率極高,適合 GB 級大檔:

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

while ($reader->read()) {
  if ($reader->nodeType === XMLReader::ELEMENT && $reader->localName === 'article') {
    // 只讀取需要的節點展開為 DOM 片段
    $node = $reader->expand(); // 返回 DOMNode
    $title = $node->getElementsByTagName('title')->item(0)->nodeValue;
    echo "標題: $title\n";
    // 處理完釋放記憶體
    $node->parentNode->removeChild($node);
  }
}
$reader->close();
?>

四、API 選型指南

API記憶體速度功能豐富度適用場景
SimpleXML中快基礎小型配置檔、簡單 API 回應
DOMDocument高 (全載入)中完整 (XPath、Schema、XSLT)需修改結構、複雜查詢、產出漂亮 XML
XMLReader極低 (流式)快唯讀、前向大檔匯入、日誌分析、串流處理
XMLWriter極低 (流式)快唯寫大量資料匯出 XML

五、常見坑點與解決

  1. 編碼亂碼:建構 DOMDocument 時指定 new DOMDocument('1.0', 'UTF-8'),輸出前送 header('Content-Type: application/xml; charset=utf-8')。
  2. 空白文字節點干擾遍歷:使用 $element->childNodes 時會包含換行文字節點,改用 $element->getElementsByTagName('*') 或檢查 nodeType === XML_ELEMENT_NODE。
  3. 實體未定義錯誤:載入含自訂實體的 XML 前,設定 $dom->substituteEntities = true; 或預先載入 DTD。
  4. 大檔案記憶體耗盡:強制改用 XMLReader/XMLWriter 流式處理。

結語

掌握 DOMDocument 為主、SimpleXML 輔、XMLReader/Writer 應對大檔 的組合策略,即可輕鬆應對 PHP 專案中 99% 的 XML 處理需求。建議新專案優先使用 DOMDocument + XPath,代碼可維護性與擴充性最佳。

copyright © 萬盛學電腦網 all rights reserved