Parsing XML with DOM

The DOM parser provided in PHP is much simpler to use, but what you take out in complexity comes back in memory usage—in spades. Instead of firing events and allowing you to handle the document as it’s being parsed, the DOM parser takes an XML document and returns an entire tree of nodes and elements.

$parser = new DomDocument(  );
$rootNode = $parser->load('BookList.xml');

processNodes($rootNode);

function processNodes($node) {
  $children = $node->children;

  foreach ($children as $child) {
    if ($child->nodeType == XML_TEXT_NODE) {
      echo $child->noteValue;
    }
    else if ($child->nodeType == XML_ELEMENT_NODE) {
      processNodes($child);
    }
  }
}

Get Programming PHP, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.