SimpleXML 是 PHP 5+ 內建擴展,將 XML 文檔轉為可迭代的對象樹,支持 XPath、屬性訪問、命名空間,適合中小型 XML 處理 (≤ 10MB)。大文件請用 XMLReader (SAX 流式)。
<?php
// 1. 從文件載入
$xml = simplexml_load_file('sample.xml');
if ($xml === false) {
// 處理錯誤:libxml_get_errors()
foreach (libxml_get_errors() as $err) {
error_log("XML Error: {$err->message} at line {$err->line}");
}
libxml_clear_errors();
exit;
}
// 2. 直接輸出完整 XML (含聲明)
header('Content-Type: application/xml; charset=UTF-8');
echo $xml->asXML();
// 3. 或輸出格式化 HTML 預覽
echo '' . htmlspecialchars($xml->asXML()) . '
';
?>
<?xml version="1.0" encoding="UTF-8"?>
<library>
<book id="1">
<title>PHP 核心技術</title>
<author gender="female">張三</author>
<description>深入講解 PHP 內核</description>
<price currency="CNY">89.00</price>
</book>
<book id="2">
<title>MySQL 實戰 45 講</title>
<author gender="male">李四</author>
<description>從索引到架構設計</description>
<price currency="CNY">129.00</price>
</book>
</library>
foreach ($xml->book as $book) {
echo "標題: {$book->title}\n";
echo "作者: {$book->author}\n";
echo "屬性 id: {$book['id']}\n"; // 訪問屬性
echo "作者性別: {$book->author['gender']}\n"; // 子元素屬性
echo "價格: {$book->price} ({$book->price['currency']})\n";
}
// 所有價格 > 100 的書
$expensive = $xml->xpath('//book/price[. > 100]/..');
foreach ($expensive as $book) {
echo "昂貴書籍: {$book->title}\n";
}
// 所有女性作者的書
$femaleBooks = $xml->xpath('//book/author[@gender="female"]/..');
$xml->book[0]->price = '99.00';
$xml->book[0]->price['currency'] = 'USD';
$xml->asXML('sample_modified.xml'); // 保存回文件
$xml = simplexml_load_file('ns.xml');
$xml->registerXPathNamespace('dc', 'https://purl.org/dc/elements/1.1/');
$titles = $xml->xpath('//dc:title');
libxml_use_internal_errors(true); // 關閉標準錯誤輸出
$xml = simplexml_load_file('bad.xml');
if ($xml === false) {
$errors = libxml_get_errors();
foreach ($errors as $e) {
// 記錄、報警
}
libxml_clear_errors();
}
| 指標 | SimpleXML | XMLReader | DOMDocument |
|---|---|---|---|
| 解析模式 | DOM 樹 (全量載入內存) | SAX 流式 (逐節點) | DOM 樹 |
| 內存佔用 | 高 (文件大小 5-10倍) | 極低 (常數) | 高 |
| 隨機訪問 | 支援 | 不支援 (單向) | 支援 |
| XPath | 支援 | 不支援 | 支援 |
| 修改/寫入 | 簡單 | 不可 | 完整 DOM API |
| 適用場景 | 配置文件、API 響應、小文件 | 大文件、流式處理、低內存 | 複雜操作、XSLT、Schema 驗證 |
simplexml_load_file() 是 PHP 處理中小型 XML 的首選:API 直觀、支援屬性/命名空間/XPath、可直接輸出 XML。記住開啟 libxml_use_internal_errors(true) 進行優雅錯誤處理。大文件 (>50MB) 必須改用 XMLReader。