【问题标题】:how to get attributes from xml child with PHP如何使用 PHP 从 xml 子项中获取属性
【发布时间】:2014-04-26 18:18:43
【问题描述】:

我希望有人可以在这里给我一些帮助。我有这个 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

我该怎么做?

【问题讨论】:

  • 你使用的是SimpleXML还是XMLReader
  • 如果您尝试过,请在您的问题中说明您是如何尝试的:如果我们可以看到您的代码,我们可能会看到您出错的地方;但不知道自己做错了什么
  • $reader = new XMLReader(); $reader->open("data\data.xml"); while($reader->read()) { if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'ChannelStatistics') { $F1 = $reader->getAttribute('ClassId=" F1"'); $F2 = $reader->getAttribute('ClassId="F2"'); $F3 = $reader->getAttribute('ClassId="F2"'); } $reader->close();

标签: php xml


【解决方案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'] 来获取一个属性。

【讨论】:

  • 我仍然无法得到任何结果,但没有错误 $obj = simplexml_load_file('data\data.xml'); foreach($obj->ChannelStatistics as $channel){ echo $channel->attributes()->ChannelId; foreach($channel->DefectCounter as $defect){ echo $defect->attributes()->ClassId; } }
  • XML 文件和以下节点 /NdtReport/PieceReport/Piece/DeviceValuation/ChannelStatistics/DefectCounter
  • 好的,我得到了 DMATF1F2F3FerroF1F2F3,但没有得到 F1、F2 或 F3 的值
猜你喜欢
  • 2015-02-26
  • 2021-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-26
  • 1970-01-01
相关资源
最近更新 更多