The other day I was trying to generate a Google Sitemap XML file dynamically (not for WordPress btw) using PHP, pulling data from a MySQL database and populating the XML file with such data – as-and-when new data is entered into the database.
Sounds easy enough, but I had difficulty getting PHP to render & run properly within an XML environment. Google doesn't need the sitemap.xml to be in a .xml format, but I would presume it helps and it would look better if it were. So, here's my work-around.
Firstly, I put this chunk of code into my .htaccess file. These couple of lines tell all .xml files to render as PHP.
<Files *xml> ForceType application/x-httpd-php </Files>
Secondly, create a new file and call it sitemap.xml, then put this code at the very top.
<?php
header('Content-type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
The rest is pretty easy to be honest, just output whatever you want. Here's my example
<?php
header('Content-type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<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">';
$data = array();
$data[] = array(
'url' => 'http://www.domain.com/',
'freq' => 'weekly',
'priority' => '1.00'
);
$data[] = array(
'url' => 'http://www.domain.com/path/to/page',
'freq' => 'weekly',
'priority' => '0.80'
);foreach ($data as $d)
{
echo '<url>';
echo '<loc>'.$d['url'].'</loc>';
echo '<changefreq>'.$d['freq'].'</changefreq>';
echo '<priority>'.$d['priority'].'</priority>';
echo '</url>';
}
echo '</urlset>';
Pretty cool. Works well and (so far) Google is allowing this 100%