XML 元素常帶屬性 (如 <book id="1" category="tech">),SimpleXML 通過 attributes() 方法獲取屬性集合,返回可遍歷的 SimpleXMLElement 對象。
<?php
$xml = simplexml_load_file('books.xml');
// 獲取第一本書的 author 元素的所有屬性
$authorAttrs = $xml->book[0]->author->attributes();
// 遍歷輸出
foreach ($authorAttrs as $name => $value) {
echo "屬性名: $name, 值: $value\n";
}
// 輸出:
// 屬性名: gender, 值: female
// 直接獲取單個屬性 (字符串上下文自動轉換)
echo "性別: " . $xml->book[0]->author['gender']; // female
// 獲取所有屬性數組 (PHP 5.4+)
$attrsArray = iterator_to_array($authorAttrs);
print_r($attrsArray);
// Array ( [gender] => female )
<?xml version="1.0" encoding="UTF-8"?>
<library>
<book id="1">
<title>PHP 核心技術</title>
<author gender="female" country="CN">張三</author>
<description>深入講解 PHP 內核</description>
</book>
<book id="2">
<title>MySQL 實戰</title>
<author gender="male" country="US">John</author>
<description>從索引到架構</description>
</book>
</library>
$xml = simplexml_load_file('ns.xml');
$attrs = $xml->book[0]->attributes('https://example.com/ns', true); // 第二參數 true 表示前綴
// 或
$attrs = $xml->book[0]->attributes('prefix', true); // 已註冊前綴
foreach ($attrs as $name => $value) {
echo "$name = $value\n";
}
if (isset($xml->book[0]->author['gender'])) { ... }
// 或
if ($xml->book[0]->author->attributes()->gender) { ... }
$xml->book[0]->author['gender'] = 'unknown'; // 修改
$xml->book[0]->author->addAttribute('role', 'translator'); // 新增
$xml->asXML('books_modified.xml');
$ids = [];
foreach ($xml->book as $book) {
$ids[] = (string)$book['id']; // 強制轉字符串
}
// 或 XPath
$ids = array_map('strval', $xml->xpath('//book/@id'));
| 錯誤寫法 | 問題 | 正確寫法 |
|---|---|---|
$xml->book[0]->author->gender | 訪問子元素 <gender> 而非屬性 | $xml->book[0]->author['gender'] 或 attributes()->gender |
(int)$xml->book[0]['id'] | SimpleXMLElement 無法直接強制類型 | (int)$xml->book[0]['id'] 正確 (先轉字符串) |
json_encode($xml->attributes()) | 屬性對象無法直接 JSON 編碼 | json_encode(iterator_to_array($xml->attributes())) |
SimpleXML 訪問屬性核心語法:$element['attrName'] (單個) 或 $element->attributes() (集合遍歷)。記住:屬性用方括號/attributes(),子元素用箭頭/屬性名。配合 XPath //@attr 可批次提取。