Create Google Sitemap With PHP And Mysql

The other day we created a xml sitemap using information retrieved from a database with php, we thought we’d show you the code on how to do it:

  1. <?php
  2. $conn = mysql_connect("dblocation", "username", "password") or die('Error connecting to mysql');
  3. mysql_select_db(dbname);
  4. echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  5. echo "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
  6. $sql = "select * from tablename GROUP BY fieldname";
  7. $rs = mysql_query($sql, $conn);
  8. while($row=mysql_fetch_array($rs))  {
  9.  echo "<url>\n";
  10.  echo "<loc>http://www.your-url.com/".$row['abbr'].".html</loc>\n";
  11.  echo "<lastmod>2008-09-29</lastmod>\n";
  12.  echo "<changefreq>monthly</changefreq>\n";
  13.  echo "
  14. <priority>0.5</priority>\n";
  15.  echo "</url>\n";
  16. }
  17. echo "</urlset>" ;
  18. mysql_close($conn);
  19. ?&gt;

Save as sitemap.php and submit to search engines. Also in your robots.txt add: sitemap: http://www.your-url.com/sitemap.php

This code will return this xml source output for EACH record in your database:

<url>
<loc>http://www.your-url.com/page-path.html</loc>
<lastmod>2008-09-29</lastmod>
<changefreq>monthly</changefreq>
<priority>0.8</priority>
</url>

Posted under Web Design

This post was written by Coyol on September 30, 2008

Tags: , , ,