What are the benefits of using DOMDocument over SimpleXML for converting PHP data into XML format?

When converting PHP data into XML format, using DOMDocument over SimpleXML provides more flexibility and control over the XML structure. DOMDocument allows for easier manipulation of the XML document, such as adding, removing, and editing nodes, attributes, and values. It also offers better error handling and validation capabilities compared to SimpleXML.

// Create a new DOMDocument
$dom = new DOMDocument('1.0');

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

// Add a child element with attributes
$child = $dom->createElement('item');
$child->setAttribute('id', '1');
$child->nodeValue = 'Example';
$root->appendChild($child);

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