Generate Dynamic Sitemap in CodeIgniter

Hey mates,

We are back to the Arena yet another interesting post which would help your website SEO at a smooth pace.

We all keep updating our website more and more data gets added to our database more links get added to our website. In CMS we need not worry about indexing the new links into the Sitemap but in frameworks and Core projects, we need to generate the sitemap through online tools, again and again, to make sure search engine crawl all the links.

I myself recently got stuck in this kind of situation and found numerous libraries which allow us to dynamically generate the sitemap in CodeIgniter but many libraries contain bugs which are not easy to eliminate.

So we thought of providing a bug-free code to our young developer so they don’t face any hurdles in learning and developing fantastic stuff.

So lets start

The basic concept behind creating or generating the sitemap is to grab all the URLs or you can say slugs from the database and send them to view file responsible for generating an XML file by iterating over.

We just have to follow 4 simple steps.

  1. Gather all URLs in an array and pass them to view.
  2. Set header and generate a well-formatted XML file and iterate the loop.
  3. Call the sitemap controller at main default controller so it gets call whenever website is accessed.
  4. Specify the Sitemap URL in your robots.txt to tell search engine about your sitemap page

Let us show you how it can be done in an easy way.

As we have already mentioned let’s create a controller where we would fetch all URLs/Slugs in an array

Controller: Sitemap.php


db->select(‘slugs’)->from(‘YOUR TABLE NAME’);


//Set Header Output as XML Document
header(“Content-Type: text/xml;charset=iso-8859-1”);



In above code, we tried to fetch slug present in our table and then by setting the output header we pass the data to our view file.

Now we will create a View file and print the data in XML format.

View: sitemap.php


slug; //Gather the slug and concatenate with website URL



Now Just follow the third step and call the “Sitemap” controller at the constructor of your default controller so that if any new slugs are added to the database it can quickly add it to sitemap page.

Finally just make sure you have mentioned the new sitemap URL in your robots.txt as

This will tell the search engine to treat above URL as the sitemap of your website.

So, isn’t it’s easy to Dynamically generate the Sitemap in Codeigniter. You can Download the demo her

Hope this will help our developers.

Because we believe Hurdles aren’t really hurdles


Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *