Zend PHP 7 Certification – Data Formats and Types – DOM

This post covers the DOM section of the Data Formats and Types chapter when studying for the Zend PHP 7 Certification.

The Document Object Model (DOM) extension allows you to operate on XML documents through its DOM API.

Similar to XML Parser, it requires the libxml extension to be enabled (which it usually is by default).

To instantiate a new DOMDocument class, you can use the following code below.

$xml = new DOMDocument();

You are then able to load an xml file using the load() function. For example, see a products.xml file below.

// products.xml
<?xml version="1.0" encoding="UTF-8"?>

This file can be loaded using the following code


Note that there is also a loadXml() method that loads an xml string into a DOMDocument object.

$doc = new DOMDocument();

To add elements to the XML using the DOMDocument class, we can use the createElement() method that passes in the element name as a string.

// "Create" the document.
$xml = new DOMDocument("1.0", "UTF-8");

// Create some elements.
$xml_album = $xml->createElement("Album" );
$xml_track = $xml->createElement("Track", "The ninth symphony");

It’s worth noting that currently $xml_track is not a child of $xml_album. This will happen later on.

Setting attributes can be performed using the setAttribute() method.

// Set the attributes.
$xml_track->setAttribute("length", "0:01:15");

We can then append $xml_track to $xml_album using the appendChild() method.


// Then append $xml_album to $xml

The saveXml() method then dumps the internal XML tree back into a string.

echo $xml->saveXml();

// Outputs:
<?xml version="1.0" encoding="UTF-8"?>
    <Track length="0:01:15">The ninth symphony</Track>

PHP provides two useful functions where the DOM and SimpleXML extensions can interact.

The simplexml_import_dom() function gets a SimpleXML object from a DOMElement object.

$dom = new DOMDocument;
if (!$dom) {
    echo 'Error while parsing the document';

$s = simplexml_import_dom($dom);

echo $s->book[0]->title; // Outputs: blah

The dom_import_simplexml() function gets a DOMElement object from a SimpleXML object.

$sxe = simplexml_load_string('blah');

if ($sxe === false) {
    echo 'Error while parsing the document';

$dom_sxe = dom_import_simplexml($sxe);
if (!$dom_sxe) {
    echo 'Error while converting XML';

$dom = new DOMDocument('1.0');
$dom_sxe = $dom->importNode($dom_sxe, true);
$dom_sxe = $dom->appendChild($dom_sxe);

echo $dom->saveXML();

View the other sections:

Note: This article is based on PHP version 7.0.