Skip to content

Creating an XML sitemap with PHP

I’m trying to create a sitemap that will automatically update. I’ve done something similiar with my RSS feed, but this sitemap refuses to work. You can view it live at I think the main problem is that its not recognizing the PHP code. Here’s the full source:


include 'includes/connection.php';

header("Content-type: text/xml");

echo '<?xml version="1.0" encoding="UTF-8" ?>';


<urlset xmlns="" xmlns:xsi="" xsi:schemaLocation="">




    $entries = mysql_query("SELECT * FROM Entries");

    while($row = mysql_fetch_assoc($entries)) {
    $title = stripslashes($row['title']);
    $date = date("Y-m-d", strtotime($row['timestamp']));

    echo "


 } ?>


The problem is that the dynamic URL’s (e.g. the ones pulled from the DB) aren’t being generated and the sitemap won’t validate. Thanks!

EDIT: Right now, I’m just trying to get the code itself working. I have it set up as a PHP file on my local testing server. The code above is being used. Right now, nothing displays nothing on screen or in the source. I’m thinking I made a syntax error, but I can’t find anything. Any and all help is appreciated!

EDIT 2: Ok, I got it sorted out guys. Apparently, I had to echo the xml declaration with PHP. The final code is posted above. Thanks for your help!



If you take a look at the sitemap.xml that’s generated (using view source, in your browser, for example), you’ll see this :

<?php header('Content-type: text/xml'); ?>
<?xml version="1.0" encoding="UTF-8" ?>
<urlset xmlns="" xmlns:xsi="http:/

The <?php, present in that output, shows that PHP code is not interpreted.

This is probably because your webserver doesn’t recognize .xml as an extension of files that should contain PHP code.

At least two possible solutions :

  • Re-configure your server, so XML files go through the PHP interpreter (might not be such a good idea : that can cause problems with existing files ! )
  • Change the extension of your sitemap, to sitemap.php for example, so it’s interpreted by your server.

I would add another solution :

  • Have a sitemap.php file, that contains the code
  • And use a RewriteRule so the sitemap.xml URL actually points to the sitemap.php file

With that, you’ll have the sitemap.xml URL, which is nice (required ? ), but as the code will be in sitemap.php, it’ll get interpreted.

See Apache’s mod_rewrite.

2 People found this is helpful