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

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

<?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);
    }
}
?>

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" ?>' ?>

    <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>

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

(Visited 603 times, 1 visits today)

Leave a comment

Your email address will not be published. Required fields are marked *