Php 使用SimpleXML读取参数的名称

Php 使用SimpleXML读取参数的名称,php,xml,simplexml,Php,Xml,Simplexml,我收到了这份表格: <item><parameter name="a">3</parameter></item> 3 可以用SimpleXML读取“a”吗 我已经尝试过$xml->item->parameter->getName();但它只返回“参数” 提前感谢。是的,使用SimpleXML中的attributes()方法 另一种解决方案是使用xpath() xpath()总是返回数组(出错时返回false),这就是为什么需要将其分配

我收到了这份表格:

<item><parameter name="a">3</parameter></item>
3
可以用SimpleXML读取“a”吗

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


提前感谢。

是的,使用
SimpleXML中的
attributes()
方法


另一种解决方案是使用
xpath()

xpath()
总是返回数组(出错时返回false),这就是为什么需要将其分配给var,或者如果php>=5.4可以使用


可以,使用来自
SimpleXML


另一种解决方案是使用
xpath()

xpath()
总是返回数组(出错时返回false),这就是为什么需要将其分配给var,或者如果php>=5.4可以使用


了解SimpleXML函数:

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

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

了解SimpleXML函数:

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

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

xml:

xml:

echo $xml->xpath('item/parameter/@name')[0];
$attr = $xml->item->parameter->attributes();
$name = $attr['name'];
<item>
 <parameter name="a">3</parameter >
</item>
$xml = simplexml_load_string($string);
foreach($xml->parameter [0]->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
}

// output
name="a"