SimpleXML 是 PHP 5 起內建的 XML 處理擴展,以直觀的物件導向方式將 XML 文件轉為可遍歷的物件樹,極大簡化了讀取、查詢、修改與生成 XML 的工作。
@attributes。xpath() 方法,支援複雜查詢。$xml = simplexml_load_file('data.xml'); // 從檔案
$xml = simplexml_load_string($xmlString); // 從字串
echo $xml->book[0]->title; // 存取子元素
echo $xml->book[0]['isbn']; // 存取屬性
foreach ($xml->book as $book) {
echo $book->title . ' - ' . $book->author;
}
$results = $xml->xpath('//book[@category="tech"]/title');
foreach ($results as $title) echo $title;
$xml->book[0]->title = '新標題';
$newBook = $xml->addChild('book');
$newBook->addChild('title', 'PHP 進階');
$newBook->addAttribute('category', 'programming');
header('Content-Type: application/xml');
echo $xml->asXML(); // 直接輸出
$xml->asXML('new_data.xml'); // 存檔
children('ns', true) 或 registerXPathNamespace()。適合中小型 XML 文件、配置檔、API 回應(RSS、SOAP 簡易版)的快速開發。若需高效能串流處理、複雜 XSLT 轉換或混合內容模型,請改用 DOM 或 XMLReader/XMLWriter。