duanji9311 2014-04-26 18:18
浏览 38
已采纳

如何使用PHP从xml子节点获取属性

I hope someone could give me some help here. I Have this XML file witch channelStatistics is one of several children from the main node

<ChannelStatistics ChannelId="DMAT" CounterDim="">
    <TotalCount>104</TotalCount>
    <DefectCounter ClassId="F1">62</DefectCounter>
    <DefectCounter ClassId="F2">34</DefectCounter>
    <DefectCounter ClassId="F3">8</DefectCounter>
</ChannelStatistics>

<ChannelStatistics ChannelI="FERRO" CounterDim="">
    <TotalCount>17</TotalCount>
    <DefectCounter ClassId="F1">2</DefectCounter>
    <DefectCounter ClassId="F2">5</DefectCounter>
    <DefectCounter ClassId="F3">10</DefectCounter>
</ChannelStatistics>

How do I get to the specific child (ChannelStatistics) and then get the data (ClassId="F1", ClassId="F2", ClassId="F3") for different ChannelId?

I need a result like:

DMAT - F1=62 F2=34 F3=8     
FERRO - F1=2 F2=5 F3=10

How can I do it?

  • 写回答

1条回答 默认 最新

  • douju3911 2014-04-26 18:31
    关注

    Using SimpleXML:

    $obj = simplexml_load_string($str); // or use simplexml_load_file($file)
    
    foreach($obj->ChannelStatistics as $channel){
        echo $channel->attributes()->ChannelId;
    
        foreach($channel->DefectCounter as $defect){
            echo $defect->attributes()->ClassId;
        }
    }
    

    Note: the XML must have a root node, and the ChannelStatistics should be children of the root. Otherwise modify the foreach accordingly. You can also use the syntax $channel['ChannelId'] to get an attirbute.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题