Sitemap generation with Codeigniter

bmrinal picture bmrinal · Jun 25, 2012 · Viewed 35.5k times · Source

I need to generate a sitemap in a Codeigniter application. I found a few libraries but all of them are outdated and have bug.

Do I really need a separate library for this?

I want to know the best way to generate the sitemap in Codeigniter.

Answer

roev picture roev · Jun 25, 2012

You can use my code:

controllers/seo.php

Class Seo extends CI_Controller {

    function sitemap()
    {

        $data = "";//select urls from DB to Array
        header("Content-Type: text/xml;charset=iso-8859-1");
        $this->load->view("sitemap",$data);
    }
}

views/sitemap.php

<?= '<?xml version="1.0" encoding="UTF-8" ?>' ?>

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc><?= base_url();?></loc> 
        <priority>1.0</priority>
    </url>

    <!-- My code is looking quite different, but the principle is similar -->
    <?php foreach($data as $url) { ?>
    <url>
        <loc><?= base_url().$url ?></loc>
        <priority>0.5</priority>
    </url>
    <?php } ?>

</urlset>

add line to config/routes.php

$route['seo/sitemap\.xml'] = "seo/sitemap";

Sorry if there are some errors in the code, I made it especially for you. If there are errors, you can fix them easily by understanding the principle.