Using DOM in PHP 5 to Read XML

If you use PHP 5, the main advantage is that libxml2 is used, a much better library than libxml. It is bundled with PHP, so no installation is required. However, the API has changed drastically. First, you instantiate a DOMDocument object, then you load() a file or loadXML() a string. All method names have changed to studly caps, and all properties are real properties, not methods like in PHP 4. The preceding code does the same as the code in the previous coding, but works under PHP 5.

Parsing XML with DOM

  $dom = new DOMDocument();
  echo '<ul>';
  foreach ($dom->getElementsByTagname('quote') as
    $element) {
    $year = $element->getAttribute('year');
    foreach (($element->childNodes) as $e) {
      if (is_a($e, 'DOMElement')) {
        if ($e->tagName == 'coding') {
          $coding = htmlspecialchars($e-
        } elseif ($e->tagName == 'author') {
          $author = htmlspecialchars($e-
    echo "<li>$author: \"$coding\" ($year)</li>";
  echo '</ul>';

Note that the listings use is_a() so that the tag names are only evaluated in nodes of the type DOMElement. This is because whitespace is considered as a DOM node (however, of type DOMText).

Although the DOM implementations of PHP 4 and PHP 5 are not compatible to each other, they are quite similar. At, you will find a wrapper that promises to make a PHP 4 DOM script compatible to a PHP 5 DOM.