What is the purpose of using DomXML to create an XML file in PHP?

DomXML in PHP is used to create XML files programmatically. This is useful when you need to generate XML data dynamically based on certain conditions or data. By using DomXML, you can easily create well-formed XML documents with nested elements, attributes, and text nodes. This can be particularly helpful when working with APIs or data interchange formats that require XML.

// Create a new XML document
$dom = new DomDocument('1.0');

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

// Create child elements
$child1 = $dom->createElement('item');
$child1->setAttribute('id', '1');
$child1->nodeValue = 'Item 1';
$root->appendChild($child1);

$child2 = $dom->createElement('item');
$child2->setAttribute('id', '2');
$child2->nodeValue = 'Item 2';
$root->appendChild($child2);

// Save the XML document to a file
$dom->save('data.xml');