How to Generate Dynamic Sitemap in CodeIgniter
There are a number of benefits to using a sitemap on your website. Some of the most important ones are:
- A sitemap can improve the usability and navigation of your website.
- It can help search engines to index your site more effectively.
- It can help users to find the information they are looking for more easily.
- It can help to reduce the number of errors that occur when users try to access your site.
- A sitemap can also help to improve the loading time of your website.
A dynamic sitemap is a great way to improve the usability and navigation of your website. It allows users to easily find the information they are looking for, and it can also help search engines to index your site more effectively. In CodeIgniter, you can easily create a dynamic sitemap by using the URL helper.
What we need to do is to generate records via a controller and map them to a view as XML data.
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); } }
Then add the controller to routes inĀ application/config/routes.php
:
//add route $route['sitemap\.xml'] = "sitemap/index";
View file: sitemap.php:
<?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>daily</changefreq> <priority>1</priority> </url> <?php } ?> </urlset>