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 a block element?
<div> <img> <span>
<div>Web Programming and Development</div>
Which CSS code displays the text underlined?
font-style: italic; text-decoration: underline; font-weight: 500;
h2 {
  text-decoration: underline;
}
Click on the JavaScript function that can access other function after a specified time.
insertBefore() setTimeout() querySelector()
function someFunction() { alert("CoursesWeb.net"); }
setTimeout("someFunction()", 2000);
Click on the instruction that returns the number of items of a multidimensional array in PHP.
count($array) count($array, 1) strlen()
$food =["fruits" =>["banana", "apple"), "veggie" =>["collard", "pea"));
$nr_food = count($food, 1);
echo $nr_food;       // 6
PHP XML DOM

Last accessed pages

  1. CSS cursor property - Custom Cursors (5722)
  2. PhpSpreadsheet - Read, Write Excel and LibreOffice Calc files (26016)
  3. Vue JS - Short presentation (390)
  4. Delete multiple consecutive characters and Split long words in JavaScript (595)
  5. Lessons Adobe Flash CS5 course (3432)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (334)
  2. Read Excel file data in PHP - PhpExcelReader (127)
  3. The Four Agreements (98)
  4. PHP Unzipper - Extract Zip, Rar Archives (95)
  5. The Mastery of Love (90)
Chat
Chat or leave a message for the other users
Full screenInchide