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 is being parsed, the DOM parser takes an XML document and returns an entire tree of nodes and elements:

$parser = new DOMDocument();
$parser->load("books.xml");
processNodes($parser->documentElement);

function processNodes($node) {
  foreach ($node->childNodes as $child) {
    if ($child->nodeType == XML_TEXT_NODE) {
      echo $child->nodeValue;
}
    else if ($child->nodeType == XML_ELEMENT_NODE) {
      processNodes($child);
    }
  }
}

Get Programming PHP, 3rd 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.