Yii2 dynamic sitemap
And so let’s get started:
First, let’s create an action method in the controller SiteController
which will take data from the model and give it to the renderer. At the same time, we set the response format to the application and add a header for the client.
class SiteController extends \yii\web\Controller
…
public function actionSitemap()
{
Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
Yii::$app->response->headers->add('Content-Type', 'text/xml');
$articles = Articles::find()->all();
return $this->renderPartial('sitemap', ['articles' => $articles]);
}
Now let’s create a widget frontend/views/site/sitemap.php
<?php
/** @var \common\models\Articles[] $articles */
echo '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL ?>
<urlset xmlns="https://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://site.org/</loc>
<priority>0.0</priority>
<changefreq>daily</changefreq>
<lastmod>2022-11-15</lastmod>
</url>
<?php foreach ($articles as $article): ?>
<url>
<loc>https://site.org/articles/<?= $article->tag ?></loc>
<lastmod><?= date('Y-m-d', strtotime($article->created_at)) ?></lastmod>
</url>
<?php endforeach; ?>
</urlset>
At this stage, you can debug and see the desired result. And set up routing for the Yii2 dynamic sitemap. To do this, in main.php for example for the entire application common/config/main.php add or change the configuration urlManager
more or less like this.
'urlManager' => [
'rules' => [
'sitemap.xml' => 'site/sitemap'
],
],
This solution will solve 99% of such tasks, including building complex dynamic Yii2 sitemap trees.