What are some best practices for creating a news system using PHP to generate an XML file for external use?

When creating a news system using PHP to generate an XML file for external use, it is important to follow best practices to ensure the XML file is well-formed and easily consumable by external applications. One way to achieve this is by properly structuring the PHP code to fetch news data from a database or API, format it into XML, and output the XML file for external use.

<?php
// Connect to database or fetch news data from an API
// Create a new XML document
$xml = new DOMDocument('1.0', 'utf-8');
$news = $xml->createElement('news');
$xml->appendChild($news);

// Loop through news data and create XML nodes
foreach ($newsData as $data) {
    $article = $xml->createElement('article');
    $title = $xml->createElement('title', $data['title']);
    $content = $xml->createElement('content', $data['content']);
    $date = $xml->createElement('date', $data['date']);

    $article->appendChild($title);
    $article->appendChild($content);
    $article->appendChild($date);

    $news->appendChild($article);
}

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