如何使用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?
答
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.