Php-mysql Course

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 = https://coursesweb.net - PHP
div = https://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 is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
PHP XML DOM

Last accessed pages

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (141749)
  2. Node.js Move and Copy file (28420)
  3. MouseEvent - Events for Mouse (2909)
  4. PHPMailer (2311)
  5. Uploading images to server with Ajax (6095)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (473)
  2. CSS cursor property - Custom Cursors (79)
  3. The Mastery of Love (70)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (62)
  5. CSS3 2D transforms (46)