In this tutorial we learn the dynamic PHP script of the XML sitemap generator. A sitemap is described for navigating the website URLs. With the sitemap, the user can easily search any URL, it is very easy. Search to navigate users on the site by sitemap. you are creating in XML encoding in any project.

Here is an example of some code of how to create a dynamic XML sitemap using Codeigniter. Below is some code with which you can create a dynamic sitemap in your project via PHP.


So you can follow below steps.

Step 1. Create A Sitemap Controller File In Your Project Folder.

First of all, Add the below code in your project(controller) file and Get the data in the database you want to create sitemap URL and pass it in the view file.


<?php
defined('BASEPATH') OR exit('No direct script access allowed');`

class Sitemap extends CI_Controller {

    function __construct() {
        parent::__construct();
    }

    public function index()
    {
		$que = 'SELECT * FROM product';
        $arrData['product_detail'] = $this->db->query($que)->result_array();
		
		$this->load->view('sitemap', $arrData);
    }
}
?>


Step 2. Create Sitemap View File In Your Project Folder.

This step you can add in this bellow code in product name-wise create a dynamic XML sitemap and when this code runs at that time sitemap.xml file automatically uploaded on your root directory of the project folder.

<?php

$xmlString = '<?xml version="1.0" encoding="UTF-8"?>
    <urlset
	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"
	xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
    <loc>http://www.example.com</loc>
</url>';
foreach ($product_detail as $pd) {
    $xmlString .=   '<url>';
	$xmlString .=  '<loc>'.base_url('product/'.$pd['name'].'</loc>';
    $xmlString .=  '</url>';
}

$xmlString .= '</urlset>';

$dom = new DOMDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($xmlString);
if($dom->save($_SERVER["DOCUMENT_ROOT"].'/sitemap.xml')){
    echo "<h2>Site Map Created SuccessFully</h2>";
}else{
    echo "<h2>Site Map Created Failed</h2>";
}
?>


I hope it can help you...