如何使用XMLreader解析这个大的xml文件?

时间:2014-11-12 05:02:55

标签: php xml xmlreader

我有一个大小接近200 MB的xml文件,所以我决定使用XMLreader来提取我需要的信息。

以下是此文件中xml的片段:

<product>
  <manufacturer>Blue Widgets</manufacturer>
  <price>6.79</price>
  <condition>new</condition>
</product>
<product>
  <manufacturer>Green Widgets</manufacturer>
  <price>9.99</price>
  <condition>new</condition>
</product>
<product>
  <manufacturer>Black Widgets</manufacturer>
  <price>3.29</price>
  <condition>new</condition>
</product>
<product>
  <manufacturer>Blue Widgets</manufacturer>
  <price>14.99</price>
  <condition>new</condition>
</product>

在这个大文件中的数千条记录中,我只需要那些制造商所在的信息&#34; Blue Widgets&#34;,但我无法弄清楚如何只隔离那个制造商:

$reader = new XMLReader();
$reader->open('test.xml');

$products = array();

while($reader->read()){

      if($reader->nodeType == XMLREADER::ELEMENT && $reader->localName == 'manufacturer'){
         $reader->read();
         if($reader->value == 'Blue Widgets'){
          //Now that we know the manufacturer is right, how do I advance to the next price node within this product element?
          if($reader->nodeType == XMLREADER::ELEMENT && $reader->localName == 'price'){
              $reader->read();

              $products['price'] = $reader->value
         }
       }
     }
   }

1 个答案:

答案 0 :(得分:1)

您可以使用XMLReader::next方法。使用您的示例:

...
$reader->read();
if ($reader->value == 'Blue Widgets') {
    $reader->next('price'); // Advances cursor to the price node
}
...

文档:http://php.net/manual/en/xmlreader.next.php