How can the issue of an empty XML document in PHP be resolved when generating XML output?

When generating XML output in PHP, an empty XML document can occur if there is no data being added to the XML structure. To resolve this, you can check if there is data to be added before generating the XML output. If there is no data, you can add a default root element to ensure that the XML document is not empty.

<?php
// Check if there is data to be added to the XML structure
if($data) {
    // Generate XML output with data
    $xml = new SimpleXMLElement('<root></root>');
    // Add data to the XML structure
    // Example: $xml->addChild('element_name', 'element_value');
} else {
    // Generate XML output with default root element
    $xml = new SimpleXMLElement('<root></root>');
}

// Output the XML
header('Content-type: text/xml');
echo $xml->asXML();
?>