【问题标题】:Get node values and attributes as an array using xpath使用 xpath 将节点值和属性作为数组获取
【发布时间】:2016-06-02 06:10:04
【问题描述】:

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

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

我需要的是得到一个类似的数组

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

【问题讨论】:

  • 你用什么来解析 XML、SimpleXML、DOMXPath/DOMDocument 等等?

标签: php xml xpath


【解决方案1】:

您可以使用SimpleXMLElement 解析来做到这一点。

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

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

【讨论】:

    【解决方案2】:

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

    这里是代码

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

    $array 将产生预期的结果...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多