You can follow the following steps:
Step 1. Create a layout file sitemap.ctp for XML sitemap view
<?php
echo '<?xml version="1.0" encoding="UTF-8"?>';
echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
echo $this->fetch('content');
echo '</urlset>';
?>
Step 2. Create a separate controller for the Sitemap generation:
class SitemapsController extends AppController
{
public function index()
{
$this->viewBuilder()->setLayout('sitemap');
$this->RequestHandler->respondAs('xml');
$postTbl = TableRegistry::getTableLocator()->get('Posts');
$posts = $postTbl->find()->select(['slug']);
$this->set('posts', $posts);
//Get the base URL of your website
$url = Router::url('/', true);
$this->set('url', $url);
}
}
Step 3. Create a view file for index action containing XML tags: index.ctp
<url>
<loc><?= $url; ?></loc>
<changefreq>weekly</changefreq>
<priority>1.0</priority>
</url>
<url>
<loc><?= $url; ?>contact-us</loc>
<priority>0.5</priority>
</url>
<url>
<loc><?= $url; ?>above-us</loc>
<priority>0.5</priority>
</url>
<url>
<loc><?= $url; ?>service</loc>
<priority>0.5</priority>
</url>
<?php foreach($osts as $post){?>
<url>
<loc><?php echo $url.'blog/'.$post['slug'] ?></loc>
</url>
<?php } ?>
Step 4. Add a route for sitemap in routes.php:
Router::scope('/', function (RouteBuilder $routes) {
// Other routes.
$routes->connect('/sitemap.xml',['controller'=>'Sitemaps','action'=>'index']);
});
For the detailed tutorial, you can visit this tutorial and learn step by step how to create an XML sitemap in CakePHP.