3.1. Understanding the Document Object Model

The Document Object Model (DOM) defines the basic structure of XML. The latest version of PHP implements the DOM/XML standard exactly as released by W3C at www.w3.org/dom.

3.1.1. Reading the DOM

You can dig useful information out of the DOM in two ways:

  • Loop through the document tree

  • Search by ID or name

To loop through the entire document tree, use the getElementsByTagName() function with the wildcard character (*), as follows:

$xmlDoc = new DOMDocument("xmlsource.xml");
$nodes = xmlDoc->getElementsByTagName(*);
foreach( $nodes as $item ) {
   echo $item->getAttribute('name');
}

To search by tag name, use the same code, but replace the wildcard character (*) with the name of the tag you're searching for. The variable $nodes will contain an array of nodes that match the tag you searched for.

If you structure your XML document to key elements by ID, you can search more precisely by using the getElementByID() function. Simply replace the getElementsByTagName() function call in the preceding example with getElementByID().

3.1.2. Writing to the DOM

You might find searching through the DOM for specific information useful, but PHP really shines when you use it to write to the DOM. Writing XML manually is, at best, tedious. By using PHP, you can specify the structure of your document and let the script do the actual work of transforming raw ...

Get PHP & MySQL® Web Development All-in-One Desk Reference for Dummies® 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.