Are there any best practices or recommended approaches for automatically generating a sitemap using PHP?

Generating a sitemap in PHP involves creating an XML file that lists all the URLs of a website to help search engines index the content efficiently. One recommended approach is to dynamically generate the sitemap by fetching URLs from a database or by scanning the website's directory structure. This can be done using PHP to automate the process and ensure the sitemap stays up-to-date.

<?php
// Initialize the XML file
$xml = new DOMDocument('1.0', 'UTF-8');
$xml->formatOutput = true;

// Create the root element
$urlset = $xml->createElement('urlset');
$urlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
$xml->appendChild($urlset);

// Fetch URLs from a database or website directory
$urls = array(
    'https://example.com/page1',
    'https://example.com/page2',
    'https://example.com/page3'
);

// Add each URL to the sitemap
foreach ($urls as $url) {
    $urlElem = $xml->createElement('url');
    
    $loc = $xml->createElement('loc', $url);
    $urlElem->appendChild($loc);
    
    $urlset->appendChild($urlElem);
}

// Save the XML file
$xml->save('sitemap.xml');