首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP SimpleXML 存取 XML 屬性完整範例

     編輯:PHP 相關知識

使用 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";
}
?>

範例 XML(books.xml)

<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 資料解析的基礎技能之一。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved