How can PHP be used to automatically generate a sitemap from an existing menu or folder structure?

To automatically generate a sitemap from an existing menu or folder structure using PHP, you can recursively scan the directory structure and generate the sitemap XML file dynamically. By iterating through the folders and files, you can create the necessary XML tags for each page. This approach ensures that the sitemap stays up-to-date with the website's content without manual intervention.

<?php
function generateSitemap($path) {
    $xml = new DOMDocument('1.0', 'UTF-8');
    $urlset = $xml->createElement('urlset');
    $urlset->setAttribute('xmlns', 'http://www.sitemaps.org/schemas/sitemap/0.9');
    
    $files = scandir($path);
    foreach ($files as $file) {
        if ($file != '.' && $file != '..') {
            $url = $xml->createElement('url');
            $loc = $xml->createElement('loc', 'https://example.com/' . $file);
            $url->appendChild($loc);
            $urlset->appendChild($url);
        }
    }
    
    $xml->appendChild($urlset);
    $xml->formatOutput = true;
    $xml->save('sitemap.xml');
}

generateSitemap('/path/to/website');
?>