Skip to content

PHP XML DOM

Introduction

XML (Extensible Markup Language) is a versatile format for data exchange and storage. PHP (Hypertext Preprocessor) is a powerful server-side scripting language. Together, they work seamlessly via the PHP XML DOM extension, which provides a rich set of classes and functions for parsing, creating, modifying, and querying XML documents.

Installation

The PHP XML DOM extension is usually bundled with PHP and enabled by default. On many systems, it is provided via the php-xml package. If it is not enabled, you can activate it by uncommenting extension=dom in your php.ini file or installing the appropriate package through your package manager. Check your PHP version and extension settings, and consult your system administrator or hosting provider if necessary. Once enabled, you can start using it in your PHP scripts.

Basic Syntax

PHP XML DOM uses an object-oriented syntax, based on the Document Object Model (DOM) standard, which represents an XML document as a tree of nodes, with each node having properties and methods for manipulation. The basic syntax for creating a new DOMDocument object, loading an XML file, and accessing its nodes is as follows:

php
<?php
libxml_use_internal_errors(true);
$doc = new DOMDocument();
if ($doc->load('filename.xml')) {
    $root = $doc->documentElement;
    $children = $root->childNodes;
}
?>

This code creates a new DOMDocument object, loads an XML file named 'filename.xml', gets the root element of the document, and gets a list of its child nodes. You can then loop through the child nodes and access their properties and methods as needed.

Creating XML Documents

PHP XML DOM also provides a simple and flexible way to create XML documents from scratch, using the same object-oriented syntax. You can create new elements, attributes, text nodes, and comments, and append them to the document or to other elements. Here's an example of how to create a simple XML document with two elements:

php
<?php
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$root = $doc->createElement('root');
$doc->appendChild($root);
$child1 = $doc->createElement('child1', 'text1');
$root->appendChild($child1);
$child2 = $doc->createElement('child2', 'text2');
$root->appendChild($child2);
echo $doc->saveXML();
?>

This code creates a new DOMDocument object, creates a root element named 'root', appends it to the document, creates two child elements named 'child1' and 'child2', sets their text content to 'text1' and 'text2', respectively, and appends them to the root element. Finally, it echoes the XML code of the document, which should look like this:

xml
<root>
  <child1>text1</child1>
  <child2>text2</child2>
</root>

Saving XML Documents

After creating or modifying an XML document, you can persist it to disk using the save() method. This method writes the DOM tree to a specified file path.

php
<?php
libxml_use_internal_errors(true);
$doc = new DOMDocument('1.0', 'UTF-8');
$root = $doc->createElement('root');
$doc->appendChild($root);
$child = $doc->createElement('child', 'data');
$root->appendChild($child);

// Save to a file
if ($doc->save('output.xml')) {
    echo 'XML document saved successfully.';
} else {
    echo 'Failed to save XML document.';
}
?>

The save() method returns true on success and false on failure. Ensure the target directory is writable by your PHP process.

Modifying and Deleting Nodes

PHP XML DOM allows you to update existing nodes or remove them from the document tree. You can change text content, update attributes, or delete entire elements using standard DOM methods.

php
<?php
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->load('filename.xml');

$root = $doc->documentElement;
$child = $root->childNodes->item(0);

// Modify text content
if ($child) {
    $child->nodeValue = 'updated text';
}

// Delete a node
if ($child) {
    $root->removeChild($child);
}

$doc->save('filename.xml');
?>

This example loads an existing XML file, retrieves the first child node, updates its text content, removes it from the parent, and saves the changes back to the file. Always call save() after making structural changes to persist them.

Querying XML Documents

In addition to creating and modifying XML documents, PHP XML DOM allows you to query them using various methods and expressions, such as XPath (XML Path Language), which is a powerful and flexible language for selecting nodes and values in an XML document. You can use XPath expressions to find elements, attributes, text nodes, and comments that match certain criteria, such as a specific tag name, attribute value, or text content. Here's an example of how to use XPath to find all elements with a certain attribute value:

php
<?php
libxml_use_internal_errors(true);
$doc = new DOMDocument();
if ($doc->load('filename.xml')) {
    $xpath = new DOMXPath($doc);
    $elements = $xpath->query("//element[@attribute='value']");
    foreach ($elements as $element) {
        // do something with the element
    }
}
?>

This code loads an XML file named 'filename.xml' into a DOMDocument object, creates a new DOMXPath object with the document as its context, and uses the query method to find all elements that have an attribute named 'attribute' with a value of 'value', using an XPath expression. It then loops through the resulting NodeList of elements and performs some action on each element.

Conclusion

PHP XML DOM is a powerful and flexible extension for PHP that allows you to manipulate XML documents with ease and efficiency. Whether you need to create, modify, or query XML data, PHP XML DOM provides a rich set of classes and functions for achieving your goals. By following the best practices and techniques described in this guide, you can become a proficient and effective XML developer using PHP XML DOM. We hope you found this guide helpful and informative. If you have any feedback or suggestions, please let us know in the comments below.

Practice

What can you do with the PHP XML DOM?

Dual-run preview — compare with live Symfony routes.