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() { $this->load->database(); $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="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
.