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 W5500网线插上无反应
  • ¥15 如何用字典的Key,显示在WPF的xaml中
  • ¥15 weautomate读取Excel表格信息然后填写到网页一直报错,如何解决?
  • ¥15 C#如何在Webview2中获取网页验证码
  • ¥15 esp32烧录失败,具体情况在图片上
  • ¥15 selenium安装报错
  • ¥15 在node.js中无法安装yarn
  • ¥15 python程序修改