Generate dynamic sitemap in CodeIgniter

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

Here are steps to create dynamic sitemap

Step 1: Create 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()
    {
        $this->load->database();
        $query = $this->db->get("articles");
        $data['articles'] = $query->result();

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

Step 2: Create 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="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc><?php echo base_url();?></loc>
        <priority>1.0</priority>
        <changefreq>daily</changefreq>
    </url>
    
    <?php foreach($articles as $article) { ?>
    <url>
        <loc><?php echo base_url()."article/".$article->id ?></loc>
        <lastmod><?php echo date('c', $article->date); ?></lastmod>     
        <changefreq>weekly</changefreq>
        <priority>0.5</priority>
    </url>
    <?php } ?>
</urlset>

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 *

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.

Close