PHP › XML Handling in PHP

How does the DOM extension provide a more powerful and flexible alternative to SimpleXML when you need to actually modify or construct an XML document rather than only read one?

Intermediate

Answer

While SimpleXML is convenient for straightforward reading tasks, the DOM extension provides a more complete and powerful representation of an XML document as a full tree of node objects, supporting not just reading existing content but also creating brand new elements, modifying existing ones, removing nodes entirely, and precisely controlling formatting details like indentation when generating the final XML output, making it the better choice whenever a task genuinely requires constructing or significantly manipulating an XML document rather than simply extracting a few values from one that already exists.
$dom = new DOMDocument('1.0', 'UTF-8');
$root = $dom->createElement('order');
$root->setAttribute('id', '1001');
$dom->appendChild($root);
echo $dom->saveXML();
Real-world example An invoicing system builds a brand new XML invoice document from scratch using the DOM extension, programmatically creating each required element and attribute before saving the fully constructed document as a properly formatted XML file.

Common follow-ups: What is the difference between DOMDocument and DOMElement?;How do you properly format, or pretty print, the final generated XML output for improved readability?