How to Use PHP DOMDocument for XML and HTML

The PHP DOMDocument class is a powerful, built-in tool that allows developers to programmatically create, parse, and manipulate XML and HTML documents. This article explores how DOMDocument represents web documents as hierarchical node trees, demonstrating how to load existing documents, create new elements from scratch, modify attributes and text values, and save the final output.

Understanding the DOM Concept

The Document Object Model (DOM) treats XML and HTML documents as a tree structure where each branch ends in a node. A node can represent an element, an attribute, or text content. The DOMDocument class in PHP provides the interface to navigate and edit this tree.

Creating New XML or HTML Documents

To create a new document, you instantiate the DOMDocument class and use its built-in methods to generate and append elements.

// Create a new DOM document
$dom = new DOMDocument('1.0', 'utf-8');

// Format the output to be readable
$dom->formatOutput = true;

// Create the root element
$root = $dom->createElement('books');
$dom->appendChild($root);

// Create a child element
$book = $dom->createElement('book');
$root->appendChild($book);

// Add an attribute to the child element
$book->setAttribute('genre', 'fiction');

// Create and append a text node
$title = $dom->createElement('title', 'The Great Gatsby');
$book->appendChild($title);

// Output the XML
echo $dom->saveXML();

In this example: * createElement() generates a new element node. * appendChild() attaches a node to a parent node, building the hierarchy. * setAttribute() defines attributes on specific elements. * saveXML() (or saveHTML()) renders the internal tree as a string.

Loading and Parsing Existing Documents

If you need to edit or extract data from an existing file or string, DOMDocument provides loading methods that parse the source code into a manipulable node tree.

$dom = new DOMDocument();
// Suppress warnings caused by invalid HTML structures
libxml_use_internal_errors(true);
$dom->loadHTML($htmlContent);
libxml_clear_errors();

Modifying Existing Documents

Once a document is loaded, you can search for elements, update their contents, or add new elements to specific locations.

1. Finding Elements

You can locate specific nodes using getElementsByTagName() or by utilizing the DOMXPath class for complex queries.

// Find all 'book' tags
$books = $dom->getElementsByTagName('book');

foreach ($books as $book) {
    // Access attributes or children
    $genre = $book->getAttribute('genre');
}

2. Updating Values and Attributes

To modify existing node properties, select the target element and change its nodeValue or use setAttribute().

$titles = $dom->getElementsByTagName('title');
if ($titles->length > 0) {
    // Change the text content of the first title element found
    $titles->item(0)->nodeValue = "The Catcher in the Rye";
}

3. Deleting Nodes

To remove a node, you must target its parent element and use the removeChild() method.

$book = $dom->getElementsByTagName('book')->item(0);
if ($book) {
    // Access the parent and remove the child
    $book->parentNode->removeChild($book);
}

Saving the Changes

After editing the document tree, you can save the results back to a string or directly to a file.