【问题标题】:How do I parse this large xml file with XMLreader?如何使用 XMLreader 解析这个大的 xml 文件?
【发布时间】:2014-11-12 05:02:55
【问题描述】:

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

这是此文件中 xml 的 sn-p:

<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>

在这个大文件中的数千条记录中,我只需要制造商为“Blue Widgets”的信息,但我无法弄清楚如何仅隔离该制造商:

$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
         }
       }
     }
   }

【问题讨论】:

    标签: php xml xmlreader


    【解决方案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

    【讨论】:

      猜你喜欢
      • 2020-08-19
      • 1970-01-01
      • 1970-01-01
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-14
      • 2012-08-11
      相关资源
      最近更新 更多