What are the best practices for generating valid XML in PHP using classes or functions like DOMDocument?

Generating valid XML in PHP using classes like DOMDocument involves creating a new instance of DOMDocument, creating elements and attributes, and appending them to the document. It is important to properly handle special characters and ensure that the generated XML follows the XML specification to avoid parsing errors.

// Create a new DOMDocument
$doc = new DOMDocument('1.0', 'UTF-8');

// Create root element
$root = $doc->createElement('root');
$doc->appendChild($root);

// Create child element with text content
$child = $doc->createElement('child', 'Text content');
$root->appendChild($child);

// Create an attribute for the child element
$child->setAttribute('attribute', 'value');

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