Simple steps to create a dynamic XML sitemap in Codeigniter 4

             A Codeigniter 4 sitemap is a document containing your website's URLs. Search engines like Google, Yahoo, and Bing use this file to crawl your website efficiently. In a sitemap file, you can include additional information such as the date of addition or modification, helping search engine crawlers better understand your pages' timeline.

CodeIgniter 4 Sitemap - How to Create a Dynamic XML Sitemap in Codeigniter 4

Table Of Content

1 Prerequisites

1.) PHP version of >= 8.2
2.) Composer
3.) Mysql

2 Introduction

Creating a dynamic XML sitemap in Codeigniter 4 is essential for optimizing your website for search engines. Sitemaps help search engines like Google crawl and index your site more effectively, improving your SEO and boosting the visibility of your web pages. This guide will walk you through the steps of sitemap generation with Codeigniter, and provide example code to help you get started.

3 Create / Install a Codeigniter 4 Project

3.1 Install Codeigniter 4 Project

First, make sure your computer has a composer.
Use the following command to install new Codeigniter Project.

composer create-project codeigniter4/appstarter ci-4-sitemap-app

Then, navigate to your project directory:

cd ci-4-sitemap-app

3.2 Configure Environment and MySql Database

Rename the env file to .env and set the development mode in the .env file also configure mysql:

# CI_ENVIRONMENT = production
CI_ENVIRONMENT = development


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=ci4_sitemap
DB_USERNAME=root
DB_PASSWORD=

4 Create Migration and Model

Create a migration for the posts table and a model to manage data:

php spark make:model PostModel

Edit app/Models/PostModel.php to configure the model:

<?php
namespace App\Models;

use CodeIgniter\Model;

class PostModel extends Model
{
    protected $table = 'posts';
    protected $primaryKey = 'id';
    protected $allowedFields = ['name', 'slug', 'description', 'created_at'];
}

Create a migration file for the posts table:

php spark make:migration AddPost

Edit the migration file to define the table structure:

<?php
namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddUser extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type' => 'BIGINT',
                'constraint' => 255,
                'unsigned' => true,
                'auto_increment' => true
            ],
            'name' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'slug' => [
                'type' => 'VARCHAR',
                'constraint' => '255',
            ],
            'description' => [
                'type' => 'longtext'
            ],
            'created_at' => [
                'type' => 'TIMESTAMP',
                'null' => true
            ],
            'updated_at' => [
                'type' => 'TIMESTAMP',
                'null' => true
            ],
        ]);
        $this->forge->addPrimaryKey('id');
        $this->forge->createTable('posts');
    }

    public function down()
    {
        $this->forge->dropTable('posts');
    }
}


Run the migration:

php spark migrate

5 Create Database Seeder

For seeding test data in the posts table, use the Seeder class:

php spark make:seeder PostSeeder

Inside the PostSeeder.php file, use the Faker library to generate fake data:

<?php
namespace App\Database\Seeds;

use CodeIgniter\Database\Seeder;
use CodeIgniter\I18n\Time;
use App\Models\PostModel;
class PostSeeder extends Seeder
{
    public function run()
    {
        $post = new PostModel;
        $faker = \Faker\Factory::create();

        for ($i = 0; $i < 100; $i++) {
          $post->save(
                [
                    'name'        =>    $faker->name,
                    'slug'        =>    $faker->slug,
                    'description' => $faker->text,
                    'created_at'  =>    Time::createFromTimestamp($faker->unixTime()),
                    'updated_at'  =>    Time::now()
                ]
            );
        }
    }
}

Run this below command to insert the data.

php spark db:seed PostSeeder

6 Create New Controller - Sitemap

Create a controller to handle sitemap requests:

php spark make:controller Sitemap 

In app/Controllers/Sitemap.php, define the index function:

<?php
namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\PostModel;

class Sitemap extends BaseController
{
    public function index()
    {
        $post = new PostModel();
        $data = [
            'posts' => $post->findAll(),
        ];
        return view('index', $data);
    }
}
?>

7 Create a View

Create the index.php view file in app/Views/ to generate the dynamic XML sitemap:

    <?php 
  echo '<?xml version="1.0" encoding="UTF-8"?>';
?>

<urlset
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
  xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"
  >
  <url>
    <loc><?= base_url() ?></loc>
    <lastmod><?= date('Y-m-d H:i:s'); ?></lastmod>
    <changefreq>daily</changefreq>
    <priority>0.1</priority>
  </url>
  <?php foreach($posts as $item) { ?>
  <url>
    <loc><?= base_url('post/'.$item['name']) ?></loc>
    <lastmod><?= date('Y-m-d H:i:s'); ?></lastmod>
    <changefreq>daily</changefreq>
    <priority>0.5</priority>
  </url>
  <?php } ?>
</urlset>


8 Define a Route

In app/Config/Routes.php, define routes for the sitemap controller:

use CodeIgniter\Router\RouteCollection;

/**
 * @var RouteCollection $routes
 */
$routes->get('/', 'Home::index');
$routes->get('sitemap.xml', 'Sitemap::index');

9 Folder Structure

10 Run Web Server to Test the App

Use the following command to Test the App.

php spark serve

Visit the URL http://localhost:8080/index.php/sitemap.xml

11 Conclusion

This guide walked you through how to create a dynamic XML sitemap in Codeigniter 4. Generating a sitemap is an essential step for optimizing any web application, ensuring better indexing and search visibility.

Tags