How To Create Dynamic Xml Sitemap In Codeigniter


This tutorial we learn dynamic XML sitemap generator PHP script. A sitemap is described to navigate the website URLs. With the Sitemap, the user can easily search any URLs, it is very easy. Search to navigate users on the site by sitemap. it is creating in the XML coding in any project.

We have given below an example of a few codes of how to create a dynamic XML sitemap using Codeigniter. Some code is given below, using which you can create a dynamic sitemap in your project through PHP.

How To Create [ Dynamic Xml Sitemap ] In Codeigniter With Example

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

Leave a Reply

Your privacy will not be published. Required fields are marked *

We'll share your Website Only Trusted.!!

close