The XML DOM (Document Object Model) is a standard set of objects for accessing and manipulating XML documents.
The DOM extension allows you to to process XML documents in PHP 5+, you can use it to get, change, add, or delete XML elements.
In the DOM, every element is transformed into an object, and is seen like a node. Each node can have content, child nodes and parent node, starting with the root element (tag).

Creating an XML document with PHP

With the PHP DOM functions you can read an exiisting XML content, and also create new XML documents.
In the following example we create an XML document and save it in a new file.
  1. First, we create a new XML object, with the DomDocument class (which is part of the PHP).
  2. We use DomDocument methods to create and to add some elements, an attribute, and a text content (here we build a structure with HTML tags).
  3. Then, we write (save) these data on the server, in a .xml file (named "dom_example.xml"). The PHP must have CHMOD write permissions on the server.
In the script code there are more explanations.
<?php
$xml_file = 'files/dom_example.xml';            // define the directory and the name of the xml file

$xmlDoc = new DomDocument('1.0', 'utf-8');                        // create a new DOM object
$root = $xmlDoc->createElement('html');                           // create the root element
$root = $xmlDoc->appendChild($root);                              // adds the root element in the DOM object
$body = $xmlDoc->createElement('body');                           // create another element, 'body'
$body = $root->appendChild($body);                                // adds 'body' as a child element in $root
$body->setAttribute('bgcolor', '#e8e8fe');                        // sets an attribute for the 'body'
$div = $xmlDoc->createElement('div');                               // create another element, 'div'
$div = $body->appendChild($div);                                  // adds 'div' as a child element in 'body'
$text = $xmlDoc->createTextNode('coursesweb.net - PHP');      // create a text content
$text = $div->appendChild($text);                                 // adds the text content in 'p'

// save the xml content stored in $xmlDoc
if($xmlDoc->save($xml_file)) echo 'The dom_example.xml was created';
else  echo 'Error: unable to write dom_example.xml';
?>
In the $xmlDoc variable (which is a DOM object) is created the content of the XML, defining and adding each element one by one.
The save($xml_file) method saves the XML content in the path specified in $xml_file.
If you run the script above and open the "dom_example.xml", you'll see the following result.
<?xml version="1.0" encoding="utf-8"?> 
 <html>
  <body bgcolor="#e8e8fe">
   <div>coursesweb.net - PHP</div> 
  </body>
 </html>

Reading an XML document

PHP DOM can also be used to read data from an XML document.
In the next example we use the XML document saved in the "dom_example.xml" file (created by the script above).
  1. First, we create a new XML object, with the DomDocument class, and load the content of the "dom_example.xml" file in it (with the load() method).
  2. We get the root (with documentElement property) and all elements of root (with the getElementsByTagName("*")).
  3. Then, we use a foreach() instruction to loop through all these elements and output their name and value
<?php
$xml_file = 'files/dom_example.xml';            // define the directory and the name of the xml file

// create a new XML object and load the content of the XML file
$xmlDoc = new DOMDocument();
$xmlDoc->load($xml_file);

$root = $xmlDoc->documentElement;              // get the first child node (the root)
$elms = $root->getElementsByTagName("*");      // gets all elements ("*") of root

// loop through all elements stored in $elms
foreach ($elms as $item) {
  // gets the name and the value of each $item
  $tag = $item->nodeName;
  $value = $item->nodeValue;

  // outputs the $tag and $value
  echo $tag. ' = '. $value . '
'; } ?>
This code will output:
body = http://coursesweb.net - PHP
div = http://coursesweb.net - PHP

The DOM saves in system memory all hierarchical tree before starting to analyze the XML document, this thing affects the processing of XML documents that exceed the allocated memory.
• If you only want to read and output some data from a XML document, you should use the SimpleXML, which is fast and easy to use when performing basic tasks like: reading XML files, extracting data from XML strings, and editing nodes and attributes.
- SimpleXML is presented in the next lesson.

Modify XML documents

PHP DOM can also be used to modify data of an XML document.
In the next example we use the XML document saved in the "dom_example.xml" file.
  1. First, we create a new XML object, with the DomDocument class, and load the content of the "dom_example.xml" file in it (with the load() method).
  2. We get the root (with documentElement property) and all elements of root, then we use a for() instruction to loop through all these elements.
  3. When the loop reachs at the element which we want to modify, we set another value for it, create a new DIV element and add it in the XML content.
  4. We save the new content in the same XML file and display its structure.
<?php
$xml_file = 'files/dom_example.xml';            // define the directory and the name of the xml file

// create a new XML object and load the content of the XML file
$xmlDoc = new DOMDocument();
$xmlDoc->load($xml_file);

$root = $xmlDoc->documentElement;              // get the first child node (the root)
$elms = $root->getElementsByTagName("*");      // gets all elements ("*") in root
$nr_elms = $elms->length;                      // gets the number of elements

// loop through all elements stored in $elms
for($i = 0; $i<$nr_elms; $i++) {
  $node = $elms->item($i);               // gets the current node

  // if the name of the current $node is 'div', changes its value
  if($node->nodeName=='div') {
    $node->nodeValue = 'The new text value';

    // sets and add a new DIV, in the same parent node
	$new_elm = $xmlDoc->createElement('div', 'This is the new inserted DIV');
	$node->parentNode->appendChild($new_elm);
  }
}

// save the new xml content in the same file and output its structure
if($xmlDoc->save($xml_file)) {
  echo htmlentities($xmlDoc->saveXML());
}
?>
- item($i) - etrieves a node specified by index ($i).
- saveXML() - dumps the internal XML tree back into a string
This example above will output:
<html><body bgcolor="#e8e8fe"><div>The new text value</div><div>This is the new inserted DIV</div></body></html>

The DOM has many properties and methods for working with XML, some of them are used in the examples of this lesson.
For the complete list of PHP DOM functions, see the Document Object Model

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag adds a new line into a paragraph?
<b> <br> <p>
First line ...<br>
Other line...
Which CSS property can be used to add space between letters?
text-size word-spacing letter-spacing
#id {
  letter-spacing: 2px;
}
What JavaScript function can be used to get access to HTML element with a specified ID?
getElementById() getElementsByTagName() createElement()
var elm = document.getElementById("theID");
var content = elm.innerHTML;
alert(content);
Click on the "echo" correct instruction.
echo "CoursesWeb.net" echo "CoursesWeb.net"; echo ""CoursesWeb.net";
echo "Address URL: http://CoursesWeb.net";
PHP XML DOM

Last accessed pages

  1. Get the value of the selected /checked checkboxes in a form (23822)
  2. Naruto Games (1274)
  3. Follow the mouse cursor with a DIV inside a Parent (1140)
  4. Multidimensional arrays and array functions (4612)
  5. Number Lines (3459)

Popular pages this month

  1. Qwop (4175)
  2. Bubbles3 (3585)
  3. Butterfly Kyodai (2552)
  4. Zuma Deluxe (2350)
  5. Backgammon (1214)