PHP - very basic XMLReader

后端 未结 1 1767
逝去的感伤
逝去的感伤 2020-12-12 07:31

Because I will be parsing a very large XML file, I am trying to use XMLReader to retrieve the XML data, and use simpleXML to display. I have never used XMLreader, so I am si

相关标签:
1条回答
  • 2020-12-12 07:50

    Your loop condition is broken. You loop if you get an element AND that elements name is "product". The document element is "products", so the loop condition is never TRUE.

    You have to be aware that read() and next() are moving the internal cursor. If it is on a <product> node, read() will move it to the first child of that node.

    $reader = new XMLReader;
    $reader->open($file);
    $dom   = new DOMDocument;
    $xpath = new DOMXpath($dom);
    
    // look for the first product element
    while ($reader->read() && $reader->localName !== 'product') {
      continue;
    }
    
    // while you have an product element
    while ($reader->localName === 'product') {
      $node = $reader->expand($dom);
      var_dump(
        $xpath->evaluate('string(@category)', $node),
        $xpath->evaluate('string(name)', $node),
        $xpath->evaluate('number(price)', $node)
      );
      // move to the next product sibling
      $reader->next('product');
    }
    

    Output:

    string(7) "Desktop"
    string(14) " Desktop 1 (d)"
    float(499.99)
    string(6) "Tablet"
    string(12) "Tablet 1 (t)"
    float(1099.99)
    
    0 讨论(0)
提交回复
热议问题