duanji9311 2014-04-26 10: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 10: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.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部