Parsing and Creating XML with DOM

Learn how to use DOM to read all elements in the XML file and outputs them. Also how to append data to an XML file (or create a new XML file if not already exists).

  1. Using DOM to Read XML
  2. Using DOM to Write XML

Using DOM to Read 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 is quite similar.

Example: Using DOM to Read XML (from file or URL)

 $dom = new DOMDocument();
 foreach ($dom->getElementsByTagname('item') as $tags) {
  foreach (($tags->childNodes) as $tag) {
   if (is_a($tag, 'DOMElement')) {
   echo $tag->tagName . ':' .
        $tag->textContent ."<br>\n";
  echo '<hr>';

Note that the listings use is_a() so that the tag names are only evaluated in nodes of the type DOMElement. This is because whitespace is considered as a DOM node (however, of type DOMText).

Using DOM to Write XML

Apart from the read access, it is also possible to build complete XML documents from the ground up using PHP’s DOM support. This might look a bit clumsy; however, it works very well when you have to automatically parse a lot of data.

Example: Create XML File If Not Exists and Append Data

 $file = 'quotes.xml';
 $dom = new DOMDocument();

 //False means: remove the redundant whitespaces
 $dom->preserveWhiteSpace = false;
 //Format output with indentation and extra space
 $dom->formatOutput = true;

 //Create XML file if not exists
 if (! @$dom->load($file)) {
  $root = $dom->createElement('quotes');
  $root = $dom->appendChild($root);
 $quote = $dom->createElement('quote');
 $quote->setAttribute('year', 2023);
 $coding = $dom->createElement('coding');
 $coding->nodeValue = 'it is quote';
 $author = $dom->createElement('author');
 $author->nodeValue = 'brainbell';
 echo 'Quote saved.';

The preceding code saves author, quote, and year in an XML document, appending to the data already there.

The quotes.xml file contains the following data after executing the above code twice:

<?xml version="1.0"?>
  <quote year="2023">
    <coding>it is quote</coding>
  <quote year="2023">
    <coding>it is quote</coding>

Using XML: