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.
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.
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:
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.