測試資料 (person.xml)
<?xml version="1.0" encoding="UTF-8"?>
<humans>
<zhangying>
<name>張映</name>
<sex>男</sex>
<old>28</old>
</zhangying>
<tank>
<name>tank</name>
<sex>男</sex>
28
</tank>
</humans>
方法對比表
| 方法 | 記憶體 | 速度 | 易用度 | 適用場景 |
| DOMDocument | 高 (全樹載入) | 中 | 高 (DOM API) | 需修改/寫入 XML、複雜結構、XPath 查詢 |
| SimpleXML | 高 (全樹載入) | 快 | 極高 (屬性存取) | 單純讀取、結構固定、中小型 XML |
| XMLReader | 極低 (流式/拉取) | 快 | 中 (事件驅動) | 大型 XML (GB 級)、記憶體受限、只需部分資料 |
| Regex | 低 | 不定 | 低 (脆弱) | 極簡單/固定格式、不建議通用 |
1. DOMDocument (W3C 標準)
<?php
$dom = new DOMDocument();
$dom->load('person.xml');
$humans = $dom->getElementsByTagName('humans');
foreach ($humans as $human) {
$name = $human->getElementsByTagName('name')->item(0)->textContent;
$sex = $human->getElementsByTagName('sex')->item(0)->textContent;
$old = $human->getElementsByTagName('old')->item(0)->textContent;
echo "$name - $sex - $old\n";
}
// XPath 查詢更強大
$xpath = new DOMXPath($dom);
$names = $xpath->query('//name');
foreach ($names as $n) echo $n->textContent . "\n";
2. SimpleXML (最直覺)
<?php
$xml = simplexml_load_file('person.xml');
foreach ($xml as $person) {
echo "{$person->name} - {$person->sex} - {$person->old}\n";
}
// 存取屬性
// $xml->person['id']
// 命名空間需用 ->children('ns', true)
3. XMLReader (流式/拉取解析)
<?php
$reader = new XMLReader();
$reader->open('person.xml');
while ($reader->read()) {
if ($reader->nodeType === XMLReader::ELEMENT && $reader->localName === 'name') {
$reader->read(); // 移至 TEXT 節點
echo $reader->value . "\n";
}
}
// 適合大檔:只處理需要的節點,不建立完整樹
4. 正則解析 (不推薦通用)
<?php
$xml = file_get_contents('person.xml');
preg_match_all('/<name>(.*?)<\/name>/s', $xml, $names);
preg_match_all('/<sex>(.*?)<\/sex>/s', $xml, $sexes);
preg_match_all('/<old>(.*?)<\/old>/s', $xml, $olds);
foreach ($names[1] as $i => $name) {
echo "$name - {$sexes[1][$i]} - {$olds[1][$i]}\n";
}
// 缺點:巢狀結構難處理、實體編碼、CDATA、命名空間、格式變化皆會失效
選型建議
- 預設首選 SimpleXML:代碼最少、可讀性最高、效能足夠多數場景。
- 需寫入/修改/複雜查詢:用 DOMDocument + XPath。
- 大檔/串流/低記憶體:XMLReader (或 SAX 事件式 parser)。
- 絕不使用正則 解析任意 XML,維護成本極高。
編碼處理提醒
- XML 宣告
encoding="UTF-8" 必須與實際編碼一致。
- PHP 內部編碼建議統一 UTF-8:
mb_internal_encoding('UTF-8')。
simplexml_load_file 會自動處理編碼轉換;DOMDocument::load 需確保輸入為 UTF-8 或指定 LIBXML_NOERROR 配合 mb_convert_encoding。