萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 讀取 XML 屬性的正確姿勢:attributes() 方法詳解

場景

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 )

books.xml 示例

<?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>

進階用法

1. 獲取命名空間屬性

$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";
}

2. 判斷屬性是否存在

if (isset($xml->book[0]->author['gender'])) { ... }
// 或
if ($xml->book[0]->author->attributes()->gender) { ... }

3. 修改/新增屬性

$xml->book[0]->author['gender'] = 'unknown'; // 修改
$xml->book[0]->author->addAttribute('role', 'translator'); // 新增
$xml->asXML('books_modified.xml');

4. 批次獲取所有書的 ID

$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 可批次提取。

copyright © 萬盛學電腦網 all rights reserved