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 phrase, but works under PHP 5. Parsing XML with DOM (dom-read5.php)<?php $dom = new DOMDocument(); $dom->load('quotes.xml'); 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 == 'phrase') { $phrase = htmlspecialchars($e- >textContent); } elseif ($e->tagName == 'author') { $author = htmlspecialchars($e- >textContent); } } } echo "<li>$author: \"$phrase\" ($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).
|