In this tutorial, We will learn how to create a dynamic XML sitemap in CodeIgniter 3 application. We will generate sitemap XML without using any plugin or anything in the CodeIgniter.





Follow some steps:



Step 1: 

Create Route application/config/routes.php

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

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


Step 2: 

Create Sitemap Controller application/controllers/Sitemap.php

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


class Sitemap extends CI_Controller {


    /**
     * Index Page for this controller.
     *
     */
    public function index()
    {
        $this->load->database();
        $query = $this->db->get("items");
        $data['items'] = $query->result();


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



Step 3: 

Create view and generate XML File application/views/sitemap.php

<?php echo'<?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>


    <!-- Sitemap -->
    <?php foreach($items as $item) { ?>
    <url>
        <loc><?php echo base_url()."item/".$item->id ?></loc>
        <priority>0.5</priority>
        <changefreq>daily</changefreq>
    </url>
    <?php } ?>


</urlset>


Finally, You can run your application:

http://localhost/ci_project/sitemap.xml