In this tip I’m going to explain you we can create sitemap.xml for our Cakephp3  applications. This is very simple and easy to setup.

Step 1. Add sitemap.xml in your routes like bellow so we can redirect user to specific controller

$routes->connect('/sitemap.xml', ['controller' => 'MyController', 'action' => 'sitemap']);

Step 2. The load required data you want to set for sitemap eg. load list of posts you want to search engine to crawl. Also, note that we need to create a new layout for this

public function sitemap(){
   $this->viewBuilder()->layout('sitemap');
   $this->RequestHandler->respondAs('xml');
   $categories = $this->Categories->find('all', array('conditions'=>array('status'=>1)));
   $pages = $this->Pages->find('all', array('conditions'=>array('status'=>1)));
   $this->set(compact('categories', 'pages'));
}

In my case, I create simple layout file and load content in it

<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @since         0.10.0
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 */
?>
<?= $this->fetch('content') ?>

Step 3. Now open file you created when created method sitemap in your controller in my case I have file name sitemap.xml inside Template/my_controller/sitemap.ctp and add bellow code or modify code according to your need

<?php
$base = "https://mysite.com/";
?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc><?=$base?></loc>
        <changefreq>weekly</changefreq>
    </url>
  
    <?php foreach ($categories as $list):?>
    <url>
        <loc><?=$base.$list->slug?></loc>
        <changefreq>weekly</changefreq>
    </url>
    <?php endforeach; ?>
    <?php foreach ($pages as $list):?>
    <url>
        <loc><?=$base.'s/'.$list->slug?></loc>
        <changefreq>weekly</changefreq>
    </url>
    <?php endforeach; ?>
</urlset>

Now if everything working fine when you open your website and add this URL in our address bar (https://mysite.com/sitemap.xml) you get your page sitemap.

Hope this post helps you please like and share my blog :).