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 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加