兩大核心擴展對比
| 特性 | DOMDocument (DOM) | SimpleXML |
| API 風格 | W3C DOM 標準,面向對象,冗長但功能完整 | 簡單直觀,屬性訪問如對象屬性,鏈式調用 |
| 內存佔用 | 構建完整 DOM 樹,內存佔用大 | 同樣載入整個文檔,但對象結構輕量 |
| 命名空間支持 | 完整支持 registerXPathNamespace、getElementsByTagNameNS | 簡單支持,複雜命名空間處理繁瑣 |
| 寫入/修改 | 完整支持創建、修改、刪除節點/屬性 | 支持修改值、添加屬性/子節點,但結構調整受限 |
| XPath 查詢 | DOMXPath 完整支持 XPath 1.0 | xpath() 方法支持基本 XPath |
| 編碼要求 | 僅支持 UTF-8,需 mb_convert_encoding 預處理 | 同樣要求 UTF-8 |
| 適用場景 | 複雜 XML 生成/修改、SOAP、大文件流式處理 (XMLReader) | 讀取配置、解析 API 響應、簡單 XML 生成 |
DOMDocument 完整操作手冊
1. 創建與加載
<?php
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true; // 格式化輸出縮進
// 從字符串加載
$xmlString = '<?xml version="1.0"?><root><item id="1">值</item></root>';
$dom->loadXML($xmlString);
// 從文件加載
$dom->load('data.xml');
2. 核心節點操作 API
| 操作 | 方法 | 示例 |
| 創建元素節點 | createElement(name, value) | $el = $dom->createElement('item', '內容'); |
| 創建屬性節點 | createAttribute(name, value) 或 setAttribute() | $el->setAttribute('id', '2'); |
| 創建文本節點 | createTextNode(text) | $text = $dom->createTextNode('純文本'); |
| 創建 CDATA | createCDATASection(data) | $cdata = $dom->createCDATASection('<script>...'); |
| 添加子節點 | appendChild(node) | $parent->appendChild($child); |
| 插入節點(指定位置) | insertBefore(new, ref) | $parent->insertBefore($new, $ref); |
| 替換節點 | replaceChild(new, old) | $parent->replaceChild($new, $old); |
| 刪除節點 | removeChild(node) | $parent->removeChild($old); |
| 獲取屬性 | getAttribute(name) | $id = $el->getAttribute('id'); |
| 設置屬性 | setAttribute(name, value) | $el->setAttribute('class', 'active'); |
| 刪除屬性 | removeAttribute(name) | $el->removeAttribute('style'); |
| 查找元素 | getElementsByTagName(name) | $items = $dom->getElementsByTagName('item'); |
| XPath 查詢 | DOMXPath->query(expr) | $xpath->query('//item[@id="1"]'); |
3. 完整示例:構建 XML 並保存
<?php
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;
// 根節點
$root = $dom->createElement('catalog');
$dom->appendChild($root);
// 循環生成數據
$data = [
['id' => 1, 'title' => 'PHP 入門', 'price' => 59.00],
['id' => 2, 'title' => 'MySQL 實戰', 'price' => 79.00],
];
foreach ($data as $row) {
$book = $dom->createElement('book');
$book->setAttribute('id', $row['id']);
$title = $dom->createElement('title', $row['title']);
$book->appendChild($title);
$price = $dom->createElement('price', $row['price']);
$price->setAttribute('currency', 'CNY');
$book->appendChild($price);
$root->appendChild($book);
}
// 保存文件
$dom->save('books.xml');
// 或獲取字符串
$xmlStr = $dom->saveXML();
echo $xmlStr;
4. XML 轉關聯數組(通用遞歸函數)
function domToArray(DOMNode $node) {
$result = [];
// 屬性
if ($node->hasAttributes()) {
foreach ($node->attributes as $attr) {
$result['@attributes'][$attr->nodeName] = $attr->nodeValue;
}
}
// 子節點
if ($node->hasChildNodes()) {
$children = [];
foreach ($node->childNodes as $child) {
if ($child->nodeType === XML_TEXT_NODE) {
$text = trim($child->nodeValue);
if ($text !== '') {
$result['#text'] = $text;
}
continue;
}
if ($child->nodeType === XML_CDATA_SECTION_NODE) {
$result['#cdata'] = $child->nodeValue;
continue;
}
$childArray = domToArray($child);
$tag = $child->nodeName;
if (!isset($children[$tag])) {
$children[$tag] = [];
}
$children[$tag][] = $childArray;
}
// 簡化單子元素結構
foreach ($children as $tag => $arr) {
$result[$tag] = (count($arr) === 1) ? $arr[0] : $arr;
}
}
return $result;
}
// 使用
$array = domToArray($dom->documentElement);
print_r($array);
SimpleXML 快速上手
1. 加載與基本訪問
<?php
$xmlStr = '<?xml version="1.0"?><root><user id="1"><name>張三</name><age>25</age></user></root>';
// 從字符串
$xml = simplexml_load_string($xmlStr);
// 從文件
$xml = simplexml_load_file('users.xml');
// 從 DOMDocument 導入
$dom = new DOMDocument();
$dom->loadXML($xmlStr);
$xml = simplexml_import_dom($dom);
// 訪問:屬性用 ['attr'],子元素用 ->tag
echo $xml->user['id']; // 1 (字符串)
echo $xml->user->name; // 張三 (SimpleXMLElement 對象)
echo (string)$xml->user->name; // 張三 (字符串)
echo (int)$xml->user->age; // 25 (整數)
2. 遍歷與 XPath
<?php
$xml = simplexml_load_file('books.xml');
// 遍歷所有 book
foreach ($xml->book as $book) {
echo "ID: {$book['id']}, 書名: {$book->title}, 價格: {$book->price}\n";
}
// XPath 查詢價格 > 60 的書
$expensive = $xml->xpath('//book[price > 60]');
foreach ($expensive as $book) {
echo "昂貴書籍: {$book->title}\n";
}
// 命名空間處理
$xml->registerXPathNamespace('ns', 'https://example.com/ns');
$items = $xml->xpath('//ns:item');
3. 修改與生成 XML
<?php
$xml = simplexml_load_string('<root/>');
// 添加子元素
$user = $xml->addChild('user');
$user->addAttribute('id', 3);
$user->addChild('name', '李四');
$user->addChild('age', 30);
// 修改值
$xml->user[0]->name = '張三修改後';
// 輸出
header('Content-Type: application/xml; charset=utf-8');
echo $xml->asXML(); // 直接輸出字符串
// 或保存文件
$xml->asXML('updated.xml');
大文件流式處理:XMLReader / XMLWriter
當 XML 文件超過 100MB,DOM/SimpleXML 會導致內存耗盡。使用流式解析:
<?php
// XMLReader: 僅讀、前向、流式
$reader = new XMLReader();
$reader->open('huge.xml');
while ($reader->read()) {
if ($reader->nodeType === XMLReader::ELEMENT && $reader->name === 'item') {
// 只展開當前節點為 DOM 節點處理
$domNode = $reader->expand();
$dom = new DOMDocument();
$node = $dom->importNode($domNode, true);
$dom->appendChild($node);
// 處理 $dom...
$dom = null; // 釋放內存
}
}
$reader->close();
<?php
// XMLWriter: 生成大 XML 文件
$writer = new XMLWriter();
$writer->openUri('output.xml');
$writer->setIndent(true);
$writer->startDocument('1.0', 'UTF-8');
$writer->startElement('root');
for ($i = 1; $i <= 100000; $i++) {
$writer->startElement('item');
$writer->writeAttribute('id', $i);
$writer->writeElement('name', "Item $i");
$writer->endElement(); // item
// 定期 flush 釋放緩衝
if ($i % 1000 === 0) $writer->flush();
}
$writer->endElement(); // root
$writer->endDocument();
編碼坑點總結
- XML 聲明
<?xml version="1.0" encoding="GB2312"?> 必須與實際編碼一致。
- PHP 內部操作統一用 UTF-8,非 UTF-8 輸入需
mb_convert_encoding($str, 'UTF-8', 'GBK') 預轉換。
DOMDocument::loadXML() 接收的字符串必須是 UTF-8,否則會誤解析或報錯。
- 輸出時設置
header('Content-Type: application/xml; charset=utf-8')。