In this tutorial we will explain how to use PHP to create a dynamic sitemap.xml file in your website’s web root in order to submit your site’s URLs to search engines.

First we need to create the file sitemap.xml.php in our website’s root directory:

As you can see, we have set up our static pages manually, and then we loop through all the rows in the posts table to dynamically generate URLs for our blog posts. Next we need to create a sitemap.xsl file in our website’s root directory:

The sitemap.xsl document specifies styles to apply to your generated sitemap.xml document. Lastly, you need to set up your .htaccess file to allow requests for sitemap.xml to display the results of the sitemap.xml.php script:

The above example is an .htaccess file for CakePHP, but you could use the RewriteRule line that mentions sitemap.xml before other .htaccess rules as well.