为什么编码错误?

时间:2015-06-23 09:43:22

标签: php xml yii rss

我正在尝试创建RSS Feed。我使用yii框架。

这是我的部分视图

<?php
header("Content-Type: application/xml; charset=utf-8");
?>
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">

    <channel>
        <title>Newskeeper</title>
        <link>newskeeper.ru</link>
        <description>news</description>

        <?php
        $HOST = "http://newskeeper.ru/";
        $HOST_NEWS = "news#news_";
        $IMAGE_PATH = $HOST . "news/sendshow?id=";

        foreach($news as $item) {
            $date=date("D, j M Y G:i:s", $item['create_time']). " GMT";

            echo '<item>';
                echo '<title>' . utf8_encode(html_entity_decode($item['teaser_ru']))  . '</title>';
                echo '<link>' . utf8_encode(html_entity_decode($HOST .$HOST_NEWS . $item['slug'])) . '</link>';
                echo '<description>' .utf8_encode(html_entity_decode($item['text_ru'])). '</description>';
            echo '</item>';
        }
        ?>

    </channel>
</rss>

这是控制器类中的方法

public function actionRss() {
    $sql = "select id, teaser_ru, text_ru, slug, create_time from news order by create_time desc limit 10";
    $command = Yii::app()->db->createCommand($sql);
    $news = $command->queryAll();
    $this->renderPartial("_rss", array('news' => $news));
}

问题是为什么不显示俄文字母。它以错误的编码显示它们。

1 个答案:

答案 0 :(得分:0)

我发现了这个问题。我过度编码了。您需要删除utf8_encode并将第二个和第三个参数添加到html_entity_decode,因此rss feed的项应该如下所示

echo '<item>';
     echo '<title>' . html_entity_decode($item['teaser_ru'], ENT_COMPAT, 'utf-8')  . '</title>';
     echo '<link>' . html_entity_decode($HOST .$HOST_NEWS . $item['slug'], ENT_COMPAT, 'utf-8') . '</link>';
     echo '<description>' . html_entity_decode($item['text_ru'], ENT_COMPAT, 'utf-8') . '</description>';
echo '</item>';