使用 SimpleXMLElement::attributes() 方法可輕鬆取得 XML 節點的所有屬性,回傳可迭代的物件,支援陣列式存取與 foreach 遍歷。
<?php
$xml = simplexml_load_file('books.xml');
if (!$xml) die('XML 載入失敗');
// 取得第一本書的作者屬性
$authorAttrs = $xml->book[0]->author->attributes();
foreach ($authorAttrs as $name => $value) {
echo "$name = $value\n";
}
// 輸出: gender = female
// 直接存取單一屬性
echo "第一本書作者性別: " . $xml->book[0]->author['gender'] . "\n";
// 遍歷所有書的作者性別
foreach ($xml->book as $book) {
echo "《{$book->title}》作者性別: {$book->author['gender']}\n";
}
?>
<library>
<book>
<title>A</title>
<author gender="female">B</author>
<description>C</description>
</book>
<book>
<title>C</title>
<author gender="male">D</author>
<description>E</description>
</book>
<book>
<title>F</title>
<author gender="male">G</author>
<description>H</description>
</book>
</library>
attributes() 回傳 SimpleXMLElement 物件,可直接 foreach 或 ['attrName'] 存取。attributes('ns', true) 取得。null(轉字串為空)。掌握屬性存取是 XML 資料解析的基礎技能之一。