Build a simple sitemap generator with PHP

In this tutorial i will teach you how to buid a simple sitemap generator with PHP


For the beginning go to this link and enter the full http address for your site to view  sitemap.

Now go to this document and read about XML ( sitemaps format,   tag definition and other usefull things about sitemaps ). Also there you will see some simple examples of sitemaps, exactly how this file must look.

So let’s start to code :) . Below is the function for generating sitemap with commented code.

function mysitemap(){

  //you should make sitemap.xml file manual in root directory of your site
  if (($outfile = @fopen("sitemap.xml", "w")))
    //your site adress
    $sitename = "http://".$_SERVER['SERVER_NAME']."/";

    //this is begining of the document which you have seen earlier 
    $cont = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset\n\t\t" .
                "xmlns=\"\"\n\t\t" .
                "xmlns:xsi=\"\"\n\t\t" .
                "xsi:schemaLocation=\"\n\t\t\t\t" .

    @fwrite($outfile, $cont);

    //make date to xml sitemap format " 2013-01-30T20:13:50-05:00 "
    $lastmod=date("Y-m-d")."T".date("H:i:s").date("P");  //or date("c"); in PHP5

    //include in this array all your static pages
    //first empty is for root page
    $pages=array("","page 1","page 2","page 3","page 4");

      $cont = "<url>\n\t<loc>".$sitename.$pages[$i]."</loc>\n\t" .
                          "<lastmod>".$lastmod."</lastmod>\n\t" .
                          "<changefreq>monthly</changefreq>\n\t" .

      @fwrite($outfile, $cont);

    //now select from database and generate other links from your site
    $res = mysql_query("your query to select from database") or sqlerr(__FILE__, __LINE__);

    //and write all links in output file
    while ($row = mysql_fetch_array($res))
		$cont = "<url>\n\t<loc>" there should be your generated link from base  "</loc>\n\t" .
                          "<lastmod>".$lastmod."</lastmod>\n\t" .
                          "<changefreq>monthly</changefreq>\n\t" .

		@fwrite($outfile, $cont);

    //end of sitemap file
    $cont = "</urlset>";
    @fwrite($outfile, $cont);

    //close output file

It’s all. I hope that you understand what I did. If you have any questions leave a comment below.


Tags: , ,

Comments (2)


  1. Efficiently says:

    [...] A site map diagram gives an overview of the navigation structure of a website. (Image: Web Tuts) [...]

  2. Anonymous says:

    I was suggested this blog by my cousin. I’m not sure whether this post is written by him as nobody else
    know such detailed about my difficulty. You’re incredible!

Leave a Reply