simplexml_load_file($file):從檔案/URL 載入 → SimpleXMLElement 物件。simplexml_load_string($xml):從字串載入。new SimpleXMLElement($file, 0, true):從檔案建立(第 3 參數 true 表 dataIsURL)。<?xml version="1.0" standalone="yes"?>
<library>
<book>
<title>Pride and Prejudice</title>
<author gender="female">Jane Austen</author>
<description>Jane Austen's most popular work.</description>
</book>
<book>
<title>The Conformist</title>
<author gender="male">Alberto Moravia</author>
<description>Alberto Moravia's classic psyhcological novel.</description>
</book>
<book>
<title>The Sun Also Rises</title>
<author gender="male">Ernest Hemingway</author>
<description>The masterpiece that launched Hemingway's career.</description>
</book>
</library>
$xml = simplexml_load_file('books.xml');
echo '<pre>';
var_dump($xml);
輸出結構:
object(SimpleXMLElement)#1 (1) {
["book"]=>
array(3) {
[0]=> object(SimpleXMLElement)#2 (3) { ["title"]=> "Pride and Prejudice", ["author"]=> "Jane Austen", ["description"]=> "..." }
[1]=> object(SimpleXMLElement)#3 (3) { ["title"]=> "The Conformist", ["author"]=> "Alberto Moravia", ["description"]=> "..." }
[2]=> object(SimpleXMLElement)#4 (3) { ["title"]=> "The Sun Also Rises", ["author"]=> "Ernest Hemingway", ["description"]=> "..." }
}
}
// 迴圈所有 book
foreach ($xml->book as $book) {
echo (string)$book->title . "\n";
echo (string)$book->author . "\n";
// 存取屬性
echo (string)$book->author['gender'] . "\n";
}
// XPath 查詢
$femaleBooks = $xml->xpath('//book/author[@gender="female"]/..');
foreach ($femaleBooks as $b) {
echo (string)$b->title . " (female author)\n";
}
// 修改並儲存
$xml->book[0]->title = 'New Title';
$xml->asXML('books_modified.xml');
(string)$node、(int)$node。$xml->registerXPathNamespace('ns', 'https://...')。XMLReader 流式解析。SimpleXML 以極簡 API 處理 95% XML 需求,配合 XPath 強大查詢,是 PHP 處理設定檔、API 回應、RSS/Atom 的首選工具。