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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵