首页 > 解决方案 > Yii2 为站点地图渲染 xml

问题描述

我正在尝试为我的网站创建站点地图,因此我创建了一个操作以以 xml 格式呈现站点地图,但我得到了一个纯文本文件

我的行动:

public function actionIndex()
    {
        $channels = Channel::find()->all(); 

        $response = Yii::$app->response;
        $response->format = \yii\web\Response::FORMAT_XML;

        $headers = Yii::$app->response->headers;
        $headers->add('Content-Type', 'application/xml');

        return $this->renderPartial('/sitemap/_viewChannel', [
            'channels'   => $channels,
        ]);
    }

我的观点 :

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">

    <?php foreach ($channels as $channel){ ?>
        <url>
            <loc><?=Url::to(['/chn-channel/view', 't'=>$channel->channel_uid])?></loc>
            <changefreq>daily</changefreq>
        </url>
    <?php } ?>

</urlset>

但我得到一个普通的纯文本作为输出

输出 : 在此处输入图像描述

标签: yii2yii2-advanced-app

解决方案


通过更改找到解决方案:

$response = Yii::$app->response;
$response->format = \yii\web\Response::FORMAT_XML;

$headers = Yii::$app->response->headers;
$headers->add('Content-Type', 'application/xml');

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

推荐阅读