SimpleXML 是 PHP 5 內置的 XML 處理擴展,以「簡單」著稱:僅需幾行代碼即可將 XML 文檔轉為對象樹,支持直觀的屬性訪問與節點遍歷,是處理基礎 XML 任務的首選工具。
SimpleXMLElement 對象;同級重複元素 → 數組。$xml['attr'] 獲取屬性值。⚠️ 局限性:處理命名空間、複雜 Schema 驗證、大文件流式解析時,建議改用 XMLReader (Pull) 或 DOM (Tree)。
<?xml version="1.0" encoding="ISO-8859-1"?> <note> <to>George</to> <from>John</from> <heading>Reminder</heading> <body>Don't forget the meeting!</body> </note>
<?php
$xml = simplexml_load_file("note.xml");
echo "根元素: " . $xml->getName() . "<br>";
foreach ($xml->children() as $child) {
echo $child->getName() . ": " . $child . "<br>";
}
/* 輸出:
根元素: note
to: George
from: John
heading: Reminder
body: Don't forget the meeting!
*/
$xml->note['id'] 或 $xml->note->attributes()$xml->xpath('//to') 返回匹配節點數組$xml->registerXPathNamespace('ns', 'uri') 後配合 XPath 使用$xml->to = 'New Name'; $xml->asXML('new.xml');SimpleXML 函數屬於 PHP 核心,無額外擴展依賴,確保 php.ini 未禁用 simplexml 擴展即可(默認啟用)。