首页 > 解决方案 > 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 } ?>

标签: phpcodeigniterxml-sitemap

解决方案


您缺少header控制器中的设置,请像这样放置标题

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);
 }
}

您的视图文件似乎没问题。

有关更多详细信息,请参阅此链接


推荐阅读