How to generate a sitemap.xml file for a given folder using PHP?


If you want to generate a sitemap.xml file for a given folder, you can use the below PHP script. This script will crawl through a given folder and generate a sitemap.xml file that you can use to submit to search engines.

function GenerateXML()
{
    $path = 'https://www.yoursite.org/sitemaps/';
    $xml =  '<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">';
	
    $date = date("Y-m-d");
    if ($handle = opendir('.')) 
    {
        while (false !== ($file = readdir($handle))) 
        {
            $extension = pathinfo($file, PATHINFO_EXTENSION);
            if($extension == 'html')
            {
                $xml .= '<url>  
		<loc>'.$path.$file.'</loc>  
		<lastmod>'.$date.'</lastmod>  
		<changefreq>yearly</changefreq>  
		<priority>0.5</priority>  
		</url>';
            }
        }    
        closedir($handle);
    }	
    $xml .= '
</urlset>
';

   $filename = "sitemap.xml";
   $fp = fopen($filename, 'w');
   fwrite($fp, $xml);
   fclose($fp);
}

In this script, it traverses the current folder and searches for HTML files, and generates the sitemap.xml file.

,