0

我将文本作为 UTF8 存储在数据库中。

当通过 JS 将帖子发送到我的 API 时,诸如 ö 之类的符号会返回为“ö”

我的网站 html 被声明为

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

我的 API 输出带有一个声明 utf-8 的标头,如下所示:

$status_header = 'HTTP/1.1 '.$status.' '.self::getStatusCodeMessage($status);
header($status_header);
header('Content-type: ' . $content_type.'; charset=utf-8');

if ($body !== '') {
    echo $body;

我设法解决这个问题的唯一方法是在我的输出中使用 PHP 来做到这一点:

private static function fixText($text) {

        $replaceChars = array(
            "“" => "\"",
            '•' => '·',
            "â€" => "\"",
            "’" => "'",
            'ö' => 'ö',

            'â€' => "'",

            "é" => "é",
            "ë" => "ë",
            "£" => "£"
        );
        foreach($replaceChars as $oldChar => $newChar) {
            $text = str_replace($oldChar, $newChar, $text);
        }

        $text = iconv("UTF-8", "UTF-8//IGNORE", $text);
        return $text;
    }

显然这并不理想,因为我必须不断在地图上添加越来越多的符号。


更新:

开发人员偷偷添加了以下代码:

$document->text = mb_convert_encoding($document->text, mb_detect_encoding($document->text), "cp1252");

作为克服损坏的旧拉丁字符的一种方法。

4

1 回答 1

1

看到那些有趣的字符意味着你已经存储了双编码的 UTF-8。您没有展示如何将数据添加到数据库中。如果您utf8_encode()在已经 UTF-8 编码的字符串上使用,这将是您的结果。

MongoDB 只接受 UTF-8,但如果您已经收到 UTF-8 由网络服务器发送给您,您不应该再次自己编码。

代替:

header('Content-type: ' . $content_type.'; charset=utf-8');

考虑在以下位置设置默认字符集php.ini

default_charset=UTF-8
于 2013-08-06T13:51:10.587 回答