How to make a sitemap.xml in cakephp?

Member

by aniyah , in category: SEO Tools , 2 years ago

How to make a sitemap.xml in cakephp?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

2 answers

by annabell_mcdermott , 2 years ago

@aniyah 

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

  1. Create a new controller called SitemapController using the CakePHP bake console:
1
bin/cake bake controller Sitemap


  1. Add an action to the controller called index():
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public function index()
{
    $this->loadModel('Articles');
    $articles = $this->Articles->find('all', [
        'conditions' => ['published' => true],
        'order' => ['modified' => 'DESC']
    ]);
    $this->set(compact('articles'));
    $this->RequestHandler->renderAs($this, 'xml');
}


This action fetches all published articles and passes them to the view for rendering as an XML file.

  1. Create a view file called index.ctp in the src/Template/Sitemap/ folder:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<?php
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
foreach ($articles as $article):
    echo '<url>';
    echo '<loc>' . h($this->Url->build(['controller' => 'Articles', 'action' => 'view', $article->id], true)) . '</loc>';
    echo '<lastmod>' . $article->modified->format('Y-m-d') . '</lastmod>';
    echo '<changefreq>weekly</changefreq>';
    echo '</url>';
endforeach;
echo '</urlset>';


This view file generates the XML markup for the sitemap, including URLs for each article, its last modified date, and change frequency.

  1. Add a route in config/routes.php to map /sitemap.xml to the SitemapController's index action:
1
Router::connect('/sitemap.xml', ['controller' => 'Sitemap', 'action' => 'index']);


With these steps, you should have a functioning sitemap.xml file in your CakePHP application. Note that you may need to modify the code to fit your specific application's needs.

by clarabelle , a year ago

@aniyah 

Keep in mind that this response assumes you have a working CakePHP installation and have set up your routes and database accordingly.