phpcodeigniterxml-sitemap

How to create dynamic sitemap in Codeigniter


How to create a dynamic sitemap in Codeigniter. I have created a php file in Controller named it Sitemap.php and created a view named it sitemap.php everything is going well but showing the following result not the actual XML file as shown in below image. enter image description here

Codeigniter Sitemap.php file

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


 class Sitemap extends CI_Controller {


public function __construct()
{
    parent::__construct();   
    $this->load->database();
    $this->load->model('Constant_model');
    $this->load->helper('xml');

}

public function index()
{

  $query=  $this->db->query("SELECT url_slug FROM snippets UNION SELECT tag_name FROM tags");
    $data = $query->result();
    $data['items'] =$data;

    $this->load->view('sitemap', $data);
}
 }

View -> sitemap.php file

<?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->url_slug ?></loc>
    <priority>0.5</priority>
    <changefreq>daily</changefreq>
</url>
<?php } ?>


Solution

  • You are missing header setting in your controller, put the header like this

    Class Sitemap extends CI_Controller {
    
    function sitemap()
    {
        $query=  $this->db->query("SELECT url_slug FROM snippets UNION SELECT tag_name FROM tags");
        $data = $query->result();
        $data['items'] =$data;
        header("Content-Type: text/xml;charset=iso-8859-1");
        $this->load->view('sitemap', $data);
     }
    }
    

    Your view file seems to be ok.

    For more details Refer this link