You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeIgniter项目实现动态站点地图,支持URL随后台更新

Got it, let's figure out how to build a dynamic sitemap.xml for your CodeIgniter project that automatically updates when page slugs are changed in the backend. Here's a practical, step-by-step solution tailored to your needs:

Step 1: Create a Sitemap Controller

First, make a new controller to handle generating the sitemap. This controller will fetch your pages from the database, pass them to a view, and output the XML content.

Create application/controllers/Sitemap.php with this code:

<?php
class Sitemap extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('Page_model');
        // Load cache if you plan to use it (optional)
        $this->load->driver('cache');
    }

    public function index() {
        // Set the correct content type for XML
        $this->output->set_content_type('text/xml');
        
        // Fetch all published pages from your database
        $pages = $this->Page_model->get_published_pages();
        
        // Pass page data to the view
        $data['pages'] = $pages;
        $this->load->view('sitemap_view', $data);
    }
}
Step 2: Update Your Page Model

Next, add a method to your Page model that fetches all the data we need for the sitemap—including the dynamic slug, last update time, and any optional fields like priority or change frequency.

In application/models/Page_model.php, add:

public function get_published_pages() {
    // Adjust the table name and fields to match your database setup
    $this->db->select('slug, updated_at, priority, changefreq');
    $this->db->from('pages');
    $this->db->where('status', 'published'); // Only include live pages
    return $this->db->get()->result();
}
Step 3: Build the Sitemap View

Create a view that generates the actual XML structure. The key here is using CodeIgniter's site_url() function to dynamically build URLs from the slugs—this ensures that if a slug is updated in the backend, the sitemap will automatically use the new URL.

Make application/views/sitemap_view.php with:

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <!-- Add your home page explicitly -->
    <url>
        <loc><?php echo site_url(); ?></loc>
        <lastmod><?php echo date('Y-m-d'); ?></lastmod>
        <changefreq>daily</changefreq>
        <priority>1.0</priority>
    </url>

    <!-- Loop through all published pages to generate dynamic URLs -->
    <?php foreach ($pages as $page): ?>
    <url>
        <loc><?php echo site_url($page->slug); ?></loc>
        <lastmod><?php echo date('Y-m-d', strtotime($page->updated_at)); ?></lastmod>
        <changefreq><?php echo isset($page->changefreq) ? $page->changefreq : 'weekly'; ?></changefreq>
        <priority><?php echo isset($page->priority) ? $page->priority : '0.8'; ?></priority>
    </url>
    <?php endforeach; ?>
</urlset>
Step 4: Configure Routes

Add a route to map sitemap.xml to your controller's index method. Open application/config/routes.php and add:

$route['sitemap.xml'] = 'sitemap/index';

Now you can access your dynamic sitemap at yourdomain.com/sitemap.xml.

Step 5: Ensure Slug-Based Page Routing Works

Double-check that your main page routing uses slugs correctly. For example, in routes.php, you might have:

$route['(:any)'] = 'pages/view/$1';

Then in your Pages controller's view method, fetch the page by slug:

public function view($slug) {
    $page = $this->Page_model->get_page_by_slug($slug);
    // Load the page view if found, else show 404
}

This ensures that the URLs generated in the sitemap are valid and point to the correct pages.

To avoid hitting the database every time someone accesses the sitemap, add caching. Update the index method in your Sitemap controller:

public function index() {
    $cache_key = 'sitemap';
    $cached_sitemap = $this->cache->get($cache_key);

    if ($cached_sitemap) {
        $this->output->set_content_type('text/xml');
        echo $cached_sitemap;
        return;
    }

    // Generate sitemap if no cache exists
    $this->output->set_content_type('text/xml');
    $pages = $this->Page_model->get_published_pages();
    $data['pages'] = $pages;
    $sitemap_content = $this->load->view('sitemap_view', $data, true);

    // Cache for 1 hour (adjust the timeout as needed)
    $this->cache->save($cache_key, $sitemap_content, 3600);
    echo $sitemap_content;
}

Then, whenever you update a page's slug or content in the backend, clear the sitemap cache to force a refresh. Add this to your Page model's update method:

public function update_page($id, $data) {
    $this->db->where('id', $id);
    $success = $this->db->update('pages', $data);

    // Clear cache when a page is updated
    if ($success) {
        $this->cache->delete('sitemap');
    }

    return $success;
}

Now, whenever you modify a page's slug in the backend, the next time someone accesses sitemap.xml, it will generate fresh links with the updated slugs.

内容的提问来源于stack exchange,提问作者Rakesh Patil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:30:42