Tapan's World

Tapan Kumer Das

Darus Sallam, Mirpur, Dhaka, Bangladesh
Tapan Kumer Das

Creating dynamic sitemap with Codeigniter

August 2, 2015, by tapan, category CodeIgniter

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

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


class Url_model extends CI_Model{
    public function __construct(){
    public function getURLS(){
        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(){
    function sitemap()
        $data['urlslist'] = $this->url_model->getURLS();

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 yoursite.com/sitemap.xml. It can also be submitted to services like Google Webmaster tools

So, what do you think ?

%d bloggers like this: