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 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧