Tuesday, February 13, 2007

Google sitemap PHP Script

А simple PHP script for creating Google sitemaps

<?

// Connecting, selecting database
$link = mysql_connect('localhost', 'db_username', 'db_pass')
//db_username is the database username; db_pass is the database password
or die('Could not connect: ' . mysql_error());
mysql_select_db('data_base_name') or die('Could not select database');
//data_base_name is the DB you connect to

// Performing SQL query
$query = 'SELECT item_id FROM db_table_name WHERE some_condition=1';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());

// Printing results in HTML
header ("Content-type: application/xml");
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<urlset xmlns=\"http://www.google.com/schemas/sitemap/0.84\">\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC))
{
foreach ($line as $col_value)
{
echo "<url>\n";
echo "<loc>http://yoursite.com/url.php?id=$col_value</loc>\n";
echo "</url>";
}
}
echo "</urlset>\n";

// Free resultset
mysql_free_result($result);

// Closing connection
mysql_close($link);

?>

That is all. Now you have a perfect Google sitemap.

Labels: , ,