Sitemap generation with Codeigniter
Asked Answered
R

4

21

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.

Relate answered 25/6, 2012 at 8:45 Comment(0)
P
61

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.

Peavey answered 25/6, 2012 at 12:55 Comment(5)
What about multiple sitemaps if you have lots of pages/articles?Hydrated
Why is this part: '<?xml version="1.0" encoding="UTF-8" ?>' in <?= ?> echo ?Semidiurnal
Thanks a lot. It works, But It creates an error when submitting it to webmaster account says " 404 error " where as link seems to be working fine. Here is the link check and let me know infinitietech.com/sitemap.xmlReflection
This is incorrect for sites with more than 1000 paths specified.Docile
You gave a clue to me. Thanks a lot, my friend!Ventail
D
15

Must set header :

<?php header('Content-type: text/xml'); ?>
<?= '<?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>
Donative answered 16/11, 2012 at 14:25 Comment(0)
P
7

It's strongly recommended to add the link of the sitemap to the robots.txt like this:

Sitemap: http://www.yoursite.com/seo/sitemap
Pose answered 24/5, 2015 at 9:21 Comment(0)
E
1

I've written a CodeIgniter model which enabled you to call functions from a sitemap controller and spit out the XML when you're all done feeding the sitemap.

Feel free to have a look and reuse the CodeIgniter model:

https://github.com/alphabase/CodeIgniter-Sitemap-Generator

Esch answered 7/4, 2016 at 20:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.