XML 作為資料交換與配置儲存的經典格式,在 PHP 中主要透過 DOMDocument、SimpleXML、XMLReader/Writer 三大 API 處理。本文以 DOMDocument 為核心,示範從零建構、讀取、修改 XML 的完整流程,並對比各 API 適用場景。
適合結構簡單、無需複雜操作的場景:
<?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 驗證等進階需求。
<?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'); // 存檔,返回位元組數
?>
<?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";
}
?>
<?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);
?>
記憶體效率極高,適合 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 | 記憶體 | 速度 | 功能豐富度 | 適用場景 |
|---|---|---|---|---|
| SimpleXML | 中 | 快 | 基礎 | 小型配置檔、簡單 API 回應 |
| DOMDocument | 高 (全載入) | 中 | 完整 (XPath、Schema、XSLT) | 需修改結構、複雜查詢、產出漂亮 XML |
| XMLReader | 極低 (流式) | 快 | 唯讀、前向 | 大檔匯入、日誌分析、串流處理 |
| XMLWriter | 極低 (流式) | 快 | 唯寫 | 大量資料匯出 XML |
new DOMDocument('1.0', 'UTF-8'),輸出前送 header('Content-Type: application/xml; charset=utf-8')。$element->childNodes 時會包含換行文字節點,改用 $element->getElementsByTagName('*') 或檢查 nodeType === XML_ELEMENT_NODE。$dom->substituteEntities = true; 或預先載入 DTD。掌握 DOMDocument 為主、SimpleXML 輔、XMLReader/Writer 應對大檔 的組合策略,即可輕鬆應對 PHP 專案中 99% 的 XML 處理需求。建議新專案優先使用 DOMDocument + XPath,代碼可維護性與擴充性最佳。