DOMDocument
DOMDocument provides full W3C DOM API for reading and writing XML. It is more verbose than SimpleXML but offers complete control over the document structure.
DOMDocument provides full W3C DOM API for reading and writing XML. It is more verbose than SimpleXML but offers complete control over the document structure.
<?php
$dom = new DOMDocument("1.0", "UTF-8");
$dom->formatOutput = true;
$root = $dom->createElement("users");
$dom->appendChild($root);
$user = $dom->createElement("user");
$user->setAttribute("id", "1");
$root->appendChild($user);
$name = $dom->createElement("name", "Alice");
$user->appendChild($name);
echo $dom->saveXML();
// <?xml version="1.0" encoding="UTF-8"?>
// <users>
// <user id="1"><name>Alice</name></user>
// </users>
Use DOMDocument when you need to build XML programmatically or handle namespaces — SimpleXML struggles with both.