如何从xml获取属性值?

时间:2014-11-03 14:18:19

标签: php xml

我看到很多例子,但没有任何工作完美。这是解析后得到的数组。

SimpleXMLElement Object
(
[@attributes] => Array
    (
        [areaUnits] => acre
    )

)

现在我尝试获取属性,如下所示:

var_dump($list->attributes());

我收到了这个错误:

 var_dump(): Node no longer exists 

2 个答案:

答案 0 :(得分:0)

<?php
function xml_attribute($object, $attribute)
{
    if(isset($object[$attribute]))
    return (string) $object[$attribute];
}
print xml_attribute($xml, 'areaUnits'); //prints "acre"
?>

答案 1 :(得分:0)

获取SimpleXMLElement的属性非常简单。

XML:

<?xml version="1.0"?>
<root>
  <node attribute1="value1" attribute2="value2">data</node>
</root>

PHP:

// assume $xml variable contains the XML document above
$sxe = new SimpleXMLElement($xml)
$value1 = $sxe->node->attributes()->attribute1;
$value2 = $sxe->node->attributes()->attribute2;

在上面的示例中,$list必须引用实际的XML节点,以便您尝试访问其属性。根据您的错误,听起来您没有这样做,如果您在运行时修改$list引用的XML结构,通常会发生这种情况。

相关问题