Creating dynamic sitemap with Codeigniter

Recipe for creating Dynamic sitemap with CodeIgniter.

Suppose you have an articles blog where url for each article is by article ID Like .
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


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();

Create Controller for Sitemap.

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


Class Sitemap extends CI_Controller {
     public function __construct(){
         $this ->load->model( 'url_model' );
     function sitemap()
         $data [ 'urlslist' ] = $this ->url_model->getURLS();
         $this ->load->view( "sitemap_view" , $data );

Create View for Sitemap

  • Create a file named sitemap_view.php in application/views directory.
  • Display the Urls in format

<?php echo '<?xml version="1.0" encoding="UTF-8" ?>' ?>

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

Edit routes.php

  • Open routes.php in application/config directory.
  • Add the following line to routes

$route [ 'sitemap.xml' ] = "sitemap/sitemap_view" ;


Your sitemap is ready and can be accessed from It can also be submitted to services like Google Webmaster tools

(Visited 485 times, 1 visits today)

Leave a comment

Your email address will not be published.