【问题标题】:RSS from MySQL - issue with special characters来自 MySQL 的 RSS - 特殊字符问题
【发布时间】:2014-03-03 13:22:21
【问题描述】:
<?php
    header('Content-type: text/xml; charset=utf-8');
    DEFINE ('DB_USER', 'root');   
    DEFINE ('DB_PASSWORD', '');   
    DEFINE ('DB_HOST', 'localhost');   
    DEFINE ('DB_NAME', 'rss'); 
    $output  = '<?xml version="1.0" encoding="UTF-8"?>';
    $output .= '<rss version="2.0">';
    $output .= '<channel>';
    $output .= '<title>Feed Demo</title>';
    $output .= '<description>News Feed from MySQL test.</description>';
    $output .= '<language>de</language>';

    $connection = @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die('-');
    mysql_select_db(DB_NAME) or die ('-');

    $query = "SELECT * FROM entry ORDER BY date DESC";
    $result = mysql_query($query) or die ('-');

    while($row = mysql_fetch_array($result)) {
        extract($row);
        $output .= '<item>';
            $output .= '<title>' . $title . '</title>';
            $output .= '<description>' . $description . '</description>';
            $output .= '<link>' . $link . '</link>';
            $output .= '<pubDate>' . date("d. F Y, H:i", strtotime($date)) . '</pubDate>';
        $output .= '</item> ';
    } 

   $output .= '</channel>';
   $output .= '</rss>';

    echo($output);
?>

你好! 我正在使用上面的代码从 MySql 数据库生成 rss-feed。它工作得很好,直到我在条目中添加特殊字符,例如:,/,ä,ö,ü,ß,?” 等等。 我收到消息

此页面包含以下错误:

第 1 行第 377 列的错误:编码错误 带有特殊字符的行之前的所有内容都可以正常显示。

【问题讨论】:

  • 告诉您的数据库您期望 UTF-8 字符串,因为您希望将 UTF-8 字符串输出到 XML:php.net/mysql_set_charset。除了使用 XML 库生成 RSS XML 之外,SimpleXML 就足够了:php.net/simplexml

标签: php mysql xml rss feed


【解决方案1】:

您应该使用utf8_encode() 对您的所有值进行编码。

类似:

while($row = mysql_fetch_array($result)) {
    extract($row);
    $output .= '<item>';
        $output .= '<title>' . utf8_encode($title) . '</title>';
        $output .= '<description>' . utf8_encode($description) . '</description>';
        $output .= '<link>' . $link . '</link>';
        $output .= '<pubDate>' . date("d. F Y, H:i", strtotime($date)) . '</pubDate>';
    $output .= '</item> ';
} 

【讨论】:

  • 总是或仅当他的数据库表不是 UTF-8 时?
  • 好吧,这个函数应该在你使用非utf8数据并且你想将它输出为utf-8时调用
  • 错误答案和错误解释。仅适用于 Latin-1,而是设置数据库客户端字符集。答案也有误:XML 中的文本需要编码,否则您可能会在不希望的情况下注入 XML。
  • 好的@hakre,我不知道拉丁语1。非常感谢你提供的信息。但是对于XML编码,没有设置在行:$output = '&lt;?xml version="1.0" encoding="UTF-8"?&gt;';?
  • 不,您只知道文档是 UTF-8 格式(这实际上被 header('Content-type: text/xml; charset=utf-8'); 覆盖,但正如它所说的 utf-8 一样,它已被 utf-8 取代。但是那是只有提示,具体来说,所有字符串都必须在输出之前进行utf-8编码。到目前为止,您期望数据库返回您重新编码的latin-1编码字符串然后转成 utf-8。但是,告诉数据库驱动程序您需要 utf-8 字符串并让数据库重新编码。
猜你喜欢
  • 2012-04-28
  • 2011-06-09
  • 1970-01-01
  • 2015-12-31
  • 2016-09-04
  • 2016-03-07
  • 2011-04-19
相关资源
最近更新 更多