How to create a sitemap in Codeigniter?

Member

by elliott , in category: SEO , a year ago

How to create a sitemap in Codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

by ervin.williamson , a year ago

@elliott 

To create a sitemap in CodeIgniter, follow these steps:

  1. Create a sitemap controller: First, create a sitemap controller in your CodeIgniter application. Name the controller "Sitemap.php" and place it in the controllers folder.
  2. Define a function: In the sitemap controller, define a function 'index()' that will generate the sitemap XML file.
  3. Load the URL helper: To generate the URLs for your sitemap, you will need to load the URL helper in CodeIgniter. Load the URL helper in the sitemap controller constructor method.
  4. Get site URLs: In the 'index()' function, get all the URLs that you want to include in your sitemap. This could be pages, posts, categories, etc.
  5. Generate the sitemap: Once you have all the URLs, use the CI output class to generate the sitemap XML file. You can use the CI RESTful output class to automatically generate the correct content type.
  6. Test: Test your sitemap by loading http://example.com/sitemap.xml in your web browser.


Here is a basic example of a sitemap controller method in CodeIgniter:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Sitemap extends CI_Controller {

    public function __construct() {
        parent::__construct();
        // Load the URL helper
        $this->load->helper('url');
    }

    public function index() {
        // Get site URLs
        $pages = array(
            'home',
            'contact',
            'about'
        );
        
        // Generate the sitemap XML file
        $this->output
            ->set_content_type('application/xml')
            ->set_output($this->load->view('sitemap', array('pages' => $pages), true));
    }

}


This is a very basic example, but you can expand upon it by dynamically generating URLs from a database or other data source.