S
S
Sergey Erin2020-11-16 10:51:08
Yii
Sergey Erin, 2020-11-16 10:51:08

How to save XML file using Yii2?

Hello. I am creating a sitemap in the admin panel and to save the xml file in the controller I wrote:

\Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
\Yii::$app->response->headers->add('Content-Type', 'text/xml');

$xml_sitemap = $this->renderPartial('sitemap', array(
    'objects' => $objects,
));

$filepath = \Yii::$app->basePath . '/views/sitemap/sitemap.xml';
file_put_contents($filepath ,$xml_sitemap);


Sitemap.php template code:
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <?php foreach($objects as $obj) { ?>
        <url>
            <loc><?= Yii::$app->params['siteUrl'] . '/' . $obj['url']; ?></loc>
            <priority>1</priority>
        </url>
    <?php } ?>
</urlset>

Tell me, is it possible to manage in the controller without using file_put_contents() using Yii2 tools?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav, 2020-11-16
@cr1gger

It doesn't need to be saved. Immediately display in view
And in the config in urlManager write:

[
    ...
    'sitemap.xml' => 'site/sitemap'
    ...
]

And you open the link https://site.ru/sitemap.xml
You have your map there

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question