XMLReader Search

Hi guys,

Is there anyway using XMLReader (or SimpleXML for that matter) where I can search for all nodes with a particular name, rather than having to process through them each? At the moment I’m having to do:


$xml = "URI/to/XML/file";
$reader = new XMLReader;
$reader->open($xml);
$reader->open($xml);
while ($reader->read()) {
   if ($reader->nodeType == XMLREADER::ELEMENT && $reader->localName == 'ResultCode') {
      print "Found it!";
      break;
   }
}
$reader->close();

Is there a better way to do this?

Thanks guys

Sure, XPath is your friend here. :wink:


<?php
$xml = new SimpleXMLElement($file, null, true);

foreach($xml->xpath('//ResultCode') as $item){
    #use item
}
?>

Excellent. Just tried this:


<?php
            // XMLReader Example
            $stime  = microtime(TRUE);
            $reader = new XMLReader;
            $reader->xml($xml);
            while ($reader->read()) {
               if ($reader->nodeType == XMLREADER::ELEMENT && $reader->localName == $node) {
                  //echo $reader->readString().'<br>';
                  break;
               }
            }
            $reader->close();
            $etime  = microtime(TRUE) - $stime;
            echo "XMLReader: $etime<br>";
            unset($reader);

            // SimpleXMLElement Example
            $stime  = microtime(TRUE);
            $reader = new SimpleXMLElement($xml);
            foreach($reader->xpath('//ResultCode') as $item){
                //echo "$item<br>";
            }
            $etime  = microtime(TRUE) - $stime;
            echo "SimpleXMLElement: $etime<br><br><br>";
?>

The output from these examples are consistently around this (one page example):

XMLReader: 0.00028204917907715
SimpleXMLElement: 0.00014901161193848

XMLReader: 0.00050997734069824
SimpleXMLElement: 0.00013589859008789

So, my solution is anywhere between twice as slow and five times as slow (approx) to yours. Thanks :smiley:

Or even;


$xml = new DOMDocument;
$xml->load($file);

foreach($xml->getElementsByTagName('ResultCode') as $item){
    // use item
}

Of course. Was just looking at DOMDocument last week. I’ll see how it performs in relation, though I’m quite pleased with the performance of the SimpleXMLElement version