How to create sitemap xml in Codeigniter?

Member

by darion , in category: PHP Frameworks , 2 years ago

How to create sitemap xml in Codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by addison , 2 years ago

@darion 

To create a sitemap XML in Codeigniter, you can follow these steps:

  1. Create a new controller called "Sitemap" in your application/controllers directory.
  2. In the Sitemap controller, create a function called "index" which will be used to generate the sitemap XML.
  3. In the index function, load the Codeigniter XML library by adding the following line at the top of the function:
1
$this->load->library('xml');


  1. Create an array of URLs that you want to include in the sitemap. Each element of the array should have the following structure:
1
2
3
4
5
6
array(
    'loc' => 'http://www.example.com/page1',
    'lastmod' => '2022-12-23',
    'changefreq' => 'monthly',
    'priority' => '0.8'
)


  1. Use the Codeigniter XML library to generate the sitemap XML. To do this, add the following lines of code to your index function:
1
2
3
4
5
6
7
$data = array(
    'urls' => $urls
);
$this->xml->add_root('urlset');
$this->xml->add_child($data);
$this->output->set_header('Content-Type: application/xml');
$this->output->set_output($this->xml->get_xml());


  1. Save the Sitemap controller and visit the following URL in your browser to see the generated sitemap XML:
1
http://www.example.com/sitemap


Note: You will need to replace "http://www.example.com" with the base URL of your Codeigniter application.

Member

by domenico , a year ago

@darion 

To create a sitemap.xml file in CodeIgniter, you can follow these steps:


Step 1: Create a new controller file called Sitemap.php in your application/controllers directory.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
load->database();
        $this->load->helper('url');

        // Get the URLs from your database
        $urls = $this->db->select('url')->get('your_table_name')->result();

        // Create the sitemap string
        $sitemap = '';
        $sitemap .= '';

        foreach ($urls as $url) {
            $sitemap .= '';
            $sitemap .= '' . site_url($url->url) . '';
            $sitemap .= '';
        }

        $sitemap .= '';

        // Set the content-type header and output the sitemap
        header("Content-Type: text/xml");
        echo $sitemap;
    }
}


Step 2: Add a new route to your application/config/routes.php file to route requests to the Sitemap controller.

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


Step 3: Access the sitemap.xml file by visiting http://your_domain/sitemap.xml in your web browser. The controller will retrieve the URLs from your database and output them as a sitemap.xml file.


Note: Make sure to replace 'your_table_name' with the actual name of your database table that contains the URLs you want to include in the sitemap.xml file.