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 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).

TIP

Although the DOM implementations of PHP 4 and PHP 5 are not compatible to each other, they are quite similar. At http://alexandre.alapetite.net/doc-alex/domxml-php4-php5/, you will find a wrapper that promises to make a PHP 4 DOM script compatible to a PHP 5 DOM.





PHP Phrasebook
PHP Phrasebook
ISBN: 0672328178
EAN: 2147483647
Year: 2005
Pages: 193

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net