YouTube Icon

Code Playground.

How to Create Dynamic Sitemap in PHP Codeigniter?

CFG

How to Create Dynamic Sitemap in PHP Codeigniter?

A Sitemap is very important for Google, Yahoo, being SEO. every site basic requirement is sitemap because we can give XML sitemap to google web console tool. So here I would like to share with you how to create dynamic XML sitemap in CodeIgniter 3 application. we will generate sitemap XML without using any plugin or anything in CodeIgniter application.

Here, you need to simply follow few steps to add XML sitemap for SEO in PHP CodeIgniter. I simply created one table with items and getting all slug URL and make it dynamic sitemap. So you just see below code with the route, controller and view file as bellow.

Also Read:-How to Send AJAX request with CSRF token in CodeIgniter

Step 1: Create Route

we are going from scratch, we need to create one "sitemap.xml" route for access from URL. so open routes.php file and add code like as bellow:

application/config/routes.php

<?php

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

$route['default_controller'] = 'welcome';

$route['404_override'] = '';

$route['translate_uri_dashes'] = FALSE;

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

Step 2: Create Sitemap Controller

now, we have to create "Sitemap" controller with index(). so create Sitemap.php file in this path application/controllers/Sitemap.php and put bellow code in this file:

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);
    }
}

Also Read:-How to Implement Event Calendar in CodeIgniter Using jQuery

Step 3: Create XML File

In this step we will create sitemap.php view file . In this file we will write design of xml file with dynamic code. So let's update following 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>

So let's run and see how it looks your xml file.

Also Read:-How to Implement PayPal Pro Payment Gateway in CodeIgniter

you can run on following URL:

http://localhost:8000/sitemap.xml

I hop it can help you...




CFG