Generate a Dynamic Sitemap in CodeIgniter

Sitemap is a basic SEO tool for any website. It can be used to submit to search engines, which allows search engines to crawl and index your website’s content.

Here are steps to create a dynamic sitemap

Step 1: Create a sitemap controller

This controller needs to query dynamic content and load it to a view.

In application/controller/Sitemap.php

defined('BASEPATH') OR exit('No direct script access allowed');

class Sitemap extends CI_Controller {    
    public function index()
        $query = $this->db->get("articles");
        $data['articles'] = $query->result();

        $this->load->view('sitemap', $data);

Step 2: Create a sitemap view

As you see in the controller above, we need a sitemap view to display articles in XML format.

<?xml version="1.0" encoding="UTF-8">
<urlset xmlns="">
        <loc><?php echo base_url();?></loc>
    <?php foreach($articles as $article) { ?>
        <loc><?php echo base_url()."article/".$article->id ?></loc>
        <lastmod><?php echo date('c', $article->date); ?></lastmod>     
    <?php } ?>

Step 3: Add sitemap URL

Lastly, we need to create a sitemap.xml URL which maps to a controller in application/config/routes.php.

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

After all these steps, your sitemap will be available at your_domain/sitemap.xml.

Leave a Comment

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

Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.