Tags
Asked 2 years ago
30 Jun 2021
Views 322
Ila

Ila posted

How to create dynamic sitemap in Codeigniter

How to create dynamic sitemap in Codeigniter
jignesh

jignesh
answered Apr 28 '23 00:00


Creating a dynamic sitemap in CodeIgniter is quite simple. You can use the built-in library for handling XML files, as well as CodeIgniter's URL helper to generate URLs.

Here's how to create a basic dynamic sitemap in CodeIgniter:

Create a new controller method to generate the sitemap. This method should output an XML file:


public function sitemap()
{
    $this->load->helper('url');
    
    // Define your URLs here
    $urls = array(
        site_url('home'),
        site_url('about'),
        site_url('contact')
    );
    
    // Load the XML library
    $this->load->library('xml');
    
    // Create the XML document
    $xml = new SimpleXMLElement('<urlset/>');
    
    // Add each URL to the XML document
    foreach ($urls as $url) {
        $urlNode = $xml->addChild('url');
        $urlNode->addChild('loc', $url);
        $urlNode->addChild('changefreq', 'daily');
        $urlNode->addChild('priority', '1.0');
    }
    
    // Output the XML file
    header('Content-type: text/xml');
    echo $xml->asXML();
}

In the example above, we defined the URLs to include in the sitemap. You can modify this list to include your own URLs.

We used the CodeIgniter URL helper to generate the URLs. If you're not using the default URL structure, you may need to modify this code to generate the correct URLs.

The XML library is loaded and used to create the XML document. We're using the SimpleXMLElement class to create the XML nodes.

We loop through the URLs and add each one to the XML document as a <url > node. We also set the changefreq and priority values.

Finally, we output the XML file with the correct content type header.

You can access the sitemap by visiting the sitemap method in your controller. For example, if you put this method in a Main controller, you can access the sitemap by visiting http://example.com/main/sitemap.

That's it! You now have a dynamic sitemap that you can submit to search engines.
Post Answer