关于php:XML:” @ attributes”节点是什么

XML: what is the “@attributes” node

本问题已经有最佳答案,请猛点这里访问。

我有一个具有以下节点@attributes的SimpleXML对象。这是simplexml_load_string()来自从USPS获得的XML字符串的结果。

1
2
3
4
5
6
7
8
9
10
11
12
$xml =

SimpleXMLElement Object
(
    [@attributes] => Array
    (
        [CLASSID] => 3
    )

    [MailService] => Priority Mail Express 1-Day
    [Rate] => 19.10
)

我知道您可以执行以下操作

1
2
3
4
5
$temp = $xml->attributes();    // will return object with '@attributes' note
$temp = (array)$temp;    // now in array form
echo $temp['@attributes']['CLASSID'];    // prints 3

$xml->{'Rate'};    // will return the rate (19.10) as a string

是否有特定原因,为什么要为CLASSID选择@attributes?为什么不让CLASSIDMailServiceRate相同?


节点的属性与其他节点/子节点的处理方式不同。 @attributes是属性内部表示的链接。

要访问属性,请使用

1
echo $xml->attributes['CLASSID']

正如IMSop在下面的注释中指出的那样,一种更好的访问属性的方法是使用数组符号。例如,

1
echo $xml['CLASSID']