dqndc26628 2017-10-04 16:44
浏览 103
已采纳

PHP - 无法使用SimpleXML解析属性

Given the following xml:

 <data xmlns:ns2="...">
     <versions>
            <ns2:version type="HW">E</ns2:version>
            <ns2:version type="FW">3160</ns2:version>
            <ns2:version type="SW">3.4.1 (777)</ns2:version>
     </versions>
    ...
 </data>

I am trying to parse the third attribute ~ns2:version type="SW" but when running the following code I get nothing..

$s = simplexml_load_file('data.xml');

echo $s->versions[2]->{'ns2:version'};

Running this gives the following output:

$s = simplexml_load_file('data.xml');

var_dump($s->versions);

enter image description here

How can I properly get that attribute?

  • 写回答

2条回答 默认 最新

  • dtsjq28482 2017-10-04 17:21
    关注

    You've got some quite annoying XML to work with there, at least as far as SimpleXML is concerned.

    Your version elements are in the ns2 namespace, so in order to loop over them, you need to do something like this:

    $s = simplexml_load_string($xml);
    
    foreach ($s->versions[0]->children('ns2', true)->version as $child) {
      ...
    }
    

    The children() method returns all children of the current tag, but only in the default namespace. If you want to access elements in other namespaces, you can pass the local alias and the second argument true.

    The more complicated part is that the type attributes is not considered to be part of this same namespace. This means you can't use the standard $element['attribute'] form to access it, since your element and attribute are in different namespaces.

    Fortunately, SimpleXML's attributes() method works in the same way as children(), and so to access the attributes in the global namespace, you can pass it an empty string:

    $element->attributes('')->type
    

    In full, this is:

    $s = simplexml_load_string($xml);
    
    foreach ($s->versions[0]->children('ns2', true)->version as $child) {
      echo (string) $child->attributes()->type, PHP_EOL;
    }
    

    This will get you the output

    HW
    FW
    SW
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 综合布线实例设计,就好看好看不恐怖可好滤镜好聚
  • ¥15 使用moviepy库视频合并时出错
  • ¥30 FLUENT液固传质UDF
  • ¥15 怎么看梯度直方图以,怎么判断梯度消失/爆炸,怎么解决
  • ¥15 aspnetdll文件访问拒绝
  • ¥15 wpf中在模版中寻找元素
  • ¥15 MFC平台生成指定圆
  • ¥15 jmeter出现403
  • ¥500 求华为P30PRO手机硬盘数据恢复
  • ¥15 关于#vscode#的问题:ESP32开发板对接MQTT实现小灯泡的开关