Creating Dynamic sitemap with Codeigniter

Recipe for creating Dynamic sitemap with CodeIgniter.
Like yoursite.com/sitemap.xml

Example.
Suppose you have an articles blog where url for each article is by article ID Like yoursite.com/123 .
All articles are stored in articleTable of the database.

First Create a model to get URLs.

  • Create a file named url_model.php in application/models directory.
  • Get Urls from database
[php]
<?php

class Url_model extends CI_Model{

	public function __construct(){
		$this->load->database();
	}
	public function getURLS(){

		$this->db->select('articleID');
		$query=$this->db->get('articleTable');
		return $query->result_array();
	}
}
?>
[/php]

Create Controller for Sitemap.

  • Create a file named sitemap.php in application/controllers directory.
  • Get Urls from model and load them in view
[php]
<?php

Class Sitemap extends CI_Controller {

	public function __construct(){
		parent::__construct();
		$this->load->model('url_model');
	}

	function sitemap()
	{

		$data['urlslist'] = $this->url_model->getURLS();
		$this->load->view("sitemap_view",$data);
	}
}

?>

[/php]

Create View for Sitemap

  • Create a file named sitemap_view.php in application/views directory.
  • Display the Urls in format
[php]
<?php echo'<?xml version="1.0" encoding="UTF-8" ?>' ?>

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc><?php echo base_url();?></loc>
        <priority>1.0</priority>
    </url>

    <!-- Your Sitemap -->
    <?php foreach($urlslist as $url) { ?>
    <url>
        <loc><?php echo base_url()."/".$url['articleID']?></loc>
        <priority>0.5</priority>
    </url>
    <?php } ?>

</urlset>

[/php]

Edit routes.php

  • Open routes.php in application/config directory.
  • Add the following line to routes
[php]
$route['sitemap\.xml'] = "sitemap/sitemap_view";
[/php]

Your sitemap is ready and can be accessed from yoursite.com/sitemap.xml. It can also be submitted to services like Google Webmaster tools