Creating a dynamic sitemap or other xml file

29 March 2009

On a content management system you're likely to be creating and modifying your pages all the time. But what about the sitemap - do you also have to change this every time as well?

A lot of content management systems have a built in sitemap builder - but if you're creating your own content management system then you too will want to make your sitemap dynamic.

In xml you cannot call things from the database and pass in variables, and so the main file is going to be a php file.

So create your file as sitemap.php (or whatever other xml file you're trying to make dynamic).

At the very top of the document you want to tell web browsers to render this php file as an xml file.

To do this add the following few lines:

You should set HTTP header 'Content-Type: text/xml'

header('Content-Type: text/xml');

The document is now an xml file that can handle php code and so you can carry out your database queries and stll echo the results in xml.

If you still want the file to be called sitemap.xml (or whatever the xml file is called) then you need to do something in your .htaccess file, like this:

RewriteEngine on
RewriteRule ^([^/]+).xml $1.php [L]

Now any file with an xml extension will display the same filename but with a .php extension.

Please leave a comment using the form provided.

Current comments:

Dan says:

Worked great, thank you for the solution and explanation!

1 December 2010 9:08pm

Chuck says:

Peter, thanks so much for this info. I've been trying for a long while to unlock the key to dynamically generating my xml files, and this did it! Thank you for your generosity in posting this solution.

17 May 2010 5:19am