我希望有人能在这里给我一些帮助。我有这个XML文件,channelStatistics是来自主节点的几个孩子之一
<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>
如何到达特定的孩子( ChannelStatistics ),然后获取数据( ClassId =“F1”,ClassId =“F2”,ClassId =“F3”)对于不同的 ChannelId ?
我需要一个结果:
DMAT - F1=62 F2=34 F3=8
FERRO - F1=2 F2=5 F3=10
我该怎么做?
答案 0 :(得分:1)
使用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;
}
}
注意:XML必须具有根节点,ChannelStatistics应该是根的子节点。否则相应地修改foreach。您还可以使用语法$channel['ChannelId']
来获取响应。