Using DOM in PHP 4 to Read XML


 domxml_open_mem(file_get_contents('quotes.xml') 


The W3C's Document Object Model (DOM) defines a unified way to access elements in an XML structure. Therefore, accessing elements in an HTML page using JavaScript's DOM access and accessing elements in an XML file using PHP's DOM access are quite similar.

Parsing XML with DOM (dom-read4.php)
 <?php   $dom =   domxml_open_mem(file_get_contents('quotes.xml'));   echo '<ul>';   foreach ($dom->get_elements_by_tagname('quote') as     $element) {     $attr = $element->attributes();     $year = htmlspecialchars($attr[0]->value);     foreach ($element->child_nodes() as $e) {       if (isset($e->tagname)) {         if ($e->tagname == 'phrase') {           $node = $e->first_child();           $phrase = htmlspecialchars             ($node->node_value());         } elseif ($e->tagname == 'author') {           $node = $e->first_child();           $author =           htmlspecialchars($node->node_value());         }       }     }     echo "<li>$author: \"$phrase\" ($year)</li>";   }   echo '</ul>'; ?> 

Unfortunately, if you use PHP 4, be aware that the DOM access changed between versions and is not that stable on some systems. Windows users have to use extension=php_domxml.dll in php.ini and may have to copy iconv.dll in the Windows system32 folder. Other systems have to reconfigure PHP using with-dom=/path/to/libxml. Then domxml_open_file() opens a fileusing the absolute path! A more portable way is to use domxml_open_mem that reads in a string. The return value of both functions offers access to the two methods get_elements_by_tagname() and get_element_by_id() that return all nodes with a certain tag name or a specific element identified by its ID. Then each node exposes some methods such as the following:

  • first_child() First child node

  • last_child() Last child node

  • next_sibling() Next node

  • previous_sibling() Previous node

  • node_value() Value of the node

The preceding code uses DOM to access all quotes in the XML file and outputs them.




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