2015-03-02 69 views
0

我正在使用xmlReader來解析一個大的xml文件(〜100mb)。這樣使用xmlreader跳過元素php

<?xml version="1.0" encoding="ISO-8859-1"?> 
    <products> 
     <product> 
      <element_1>foo</element_1> 
      <element_2>foo</element_2> 
      <element_3>foo</element_3> 
      <element_4>foo</element_4> 
     </product> 
     <product> 
      <element_1>bar</element_1> 
      <element_2>bar</element_2> 
      <element_3>bar</element_3> 
      <element_4>bar</element_4> 
     </product> 
     <product> 
      <element_1>bar</element_1> 
      <element_2>bar</element_2> 
      <element_3>bar</element_3> 
      <element_4>bar</element_4> 
     </product> 
     <product> 
      <element_1>bar</element_1> 
      <element_2>bar</element_2> 
      <element_3>bar</element_3> 
      <element_4>bar</element_4> 
     </product> 
     <product> 
      <element_1>bar</element_1> 
      <element_2>bar</element_2> 
      <element_3>bar</element_3> 
      <element_4>bar</element_4> 
     </product> 
    </products> 

東西我們如何跳過第2種樹木和移動到第三個?

+0

跳過前2個產品樹* :) – dianikol 2015-03-02 19:21:37

回答

0

XMLReader逐行掃描您的文件。因爲你沒有在你的XML文件的任何標識符(屬性),你只能通過跳過產品1和2通過使用修復方案「下一個()」:

$xmlReader = new XMLReader; 

// try to open 
if (!$xmlReader->open($file)) { 
    die("Failed to open file"); 
} 

// read the file 
while($xmlReader->read()) { 

    // skip 1st product 
    if($xmlReader->nodeType == XMLReader::ELEMENT && $xmlReader->name == "product") {$xmlReader->next("product");} 
    // skip 2nd product 
    if($xmlReader->nodeType == XMLReader::ELEMENT && $xmlReader->name == "product") {$xmlReader->next("product");} 

    // start reading 
    if($xmlReader->nodeType == XMLReader::ELEMENT && $xmlReader->name == "product") { 
     // use your code here 

     // personally I like using simplexml from here since its easier to work with and the nodes are usually small enough 
     $node = simplexml_load_string($xmlReader->readOuterXML()); 

     // use it 
     $myNewElement1 = $node->element_1; 
     $myNewElement2 = $node->element_2; 
     $myNewElement3 = $node->element_3; 
     $myNewElement4 = $node->element_4; 
    } 
} 

也去http://php.net/manual/en/xmlreader.next.php