Create Dynamic XML Sitemap in Codeigniter App – Easily
Your dynamic website might need to have an XML Sitemap if you really care about the SEO (Search Engine Optimization). Here is how to create a dynamic XML Sitemap in the Codeigniter project easily.
Dynamic XML Sitemap in Codeigniter
Step 1: First, we need to create a Controller named Sitemap in the applications/controllers folder.
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Sitemap extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Item_model'); //Loading Items Model Class
}
public function index()
{
$this->load->helper('xml');
$data['items'] = $this->Item_model->get_all(); //Getting items list from database
$this->load->view('sitemap', $data);
}
}
Step 2: Then, create a view file in the applications/views folder and name it sitemap.php.
<?php
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
echo "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">";
echo "<url>".
"<loc>".base_url()."</loc>".
"<changefreq>daily</changefreq>".
"<priority>1</priority>".
"</url>";
if (isset($items)){
foreach($items as $item) {
echo "<url>".
"<loc>".
base_url().
"item/{$item["item_slug"]}/".
"</loc>".
"<changefreq>weekly</changefreq>".
"<priority>0.5</priority>".
"</url>";
}
}
echo "</urlset>";
?>
Step 3: Add route code to the routes.php in the applications/config folder.
$route['sitemap.xml'] = "Sitemap/index";
Now check your XML sitemap domain.com/sitemap.xml.