使用SimpleXML读取参数名称

时间:2012-07-05 09:24:32

标签: php xml simplexml

我有这样的表格:

<item><parameter name="a">3</parameter></item>

是否可以使用SimpleXML读取“a”?

我已经尝试过$ xml-&gt; item-&gt; parameter-&gt; getName();但它只返回“参数”。

提前致谢。

3 个答案:

答案 0 :(得分:4)

是的,请使用attributes()

中的SimpleXML方法

SimpleXML::attributes()

echo (string)$xml->item->parameter->attributes()->name;

codepad example


替代解决方案是使用xpath()

SimpleXML::xpath()

$name = $xml->xpath('item/parameter/@name');
echo $name[0];

codepad example

xpath()总是返回数组(如果出错则返回false),这就是为什么需要将它分配给var,或者如果你有 php&gt; = 5.4 你可以使用array dereferencing

echo $xml->xpath('item/parameter/@name')[0];

答案 1 :(得分:3)

阅读SimpleXML函数:attribute()

您可以使用它来获取元素的所有属性 在你的情况下:

$attr = $xml->item->parameter->attributes();
$name = $attr['name'];

答案 2 :(得分:0)

请参阅http://php.net/manual/en/simplexmlelement.attributes.php

的xml:

<item>
 <parameter name="a">3</parameter >
</item>

PHP:

$xml = simplexml_load_string($string);
foreach($xml->parameter [0]->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
}

// output
name="a"