使用xpath将节点值和属性作为数组获取

时间:2016-06-02 06:10:05

标签: php xml xpath

有没有办法将所有属性及其值作为数组获取。 这里我有一个节点

<vehicle wheels="four" color="red"/>

我需要的是获得像

这样的数组

$vehicle = array("wheels" => "four", "color" => "red");

2 个答案:

答案 0 :(得分:2)

您可以使用SimpleXMLElement解析来完成。

$xml = '<vehicle wheels="four" color="red"/>';

$x = new SimpleXMLElement($xml);
$array = current($x->attributes());
print_r($array);

答案 1 :(得分:0)

我使用attributes属性找到了解决方案。

这是代码

foreach ($vehicle->attributes as $attribName => $attribute_node)
{
    $array[$attribName] = $attribute_node->nodeValue;
}

$ array将产生期待的......