PHP json 编码 - 格式错误的 UTF-8 字符,可能编码不正确

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46305169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:12:40  来源:igfitidea点击:

PHP json encode - Malformed UTF-8 characters, possibly incorrectly encoded

phpjsonencodingutf-8

提问by sparkmix

I'm using json_encode($data)to an data array and there's a field contains Russian characters.

我正在使用json_encode($data)数据数组,并且有一个字段包含俄语字符。

I used this mb_detect_encoding()to display what encoding it is for that field and it displays UTF-8.

我用它mb_detect_encoding()来显示该字段的编码方式,并显示 UTF-8。

I think the json encode failed due to some bad characters in it like "ра?". I tried alot of things utf8_encodeon the data and it will by pass that error but then the data doesn't look correct anymore.

我认为 json 编码失败是因为里面有一些不好的字符,比如“ра?”。我utf8_encode在数据上尝试了很多东西,它会绕过那个错误,但是数据看起来不再正确了。

What can be done with this issue?

这个问题可以做什么?

回答by sparkmix

The issue happens if there are some non-utf8 characters inside even though most of them are utf8 chars. This will remove any non-utf8 characters and now it works.

如果里面有一些非 utf8 字符,即使其中大部分是 utf8 字符,也会出现问题。这将删除任何非 utf8 字符,现在它可以工作了。

$data['name'] = mb_convert_encoding($data['name'], 'UTF-8', 'UTF-8');

回答by Irshad Khan

If you have a multidimensional array to encode in JSON format then you can use below function:

如果您有一个多维数组以 JSON 格式编码,那么您可以使用以下函数:

If JSON_ERROR_UTF8 occurred :

如果发生 JSON_ERROR_UTF8 :

$encoded = json_encode( utf8ize( $responseForJS ) );

Below function is used to encode Array data recursively

下面的函数用于递归编码数组数据

/* Use it for json_encode some corrupt UTF-8 chars
 * useful for = malformed utf-8 characters possibly incorrectly encoded by json_encode
 */
function utf8ize( $mixed ) {
    if (is_array($mixed)) {
        foreach ($mixed as $key => $value) {
            $mixed[$key] = utf8ize($value);
        }
    } elseif (is_string($mixed)) {
        return mb_convert_encoding($mixed, "UTF-8", "UTF-8");
    }
    return $mixed;
}

回答by Tom Ah

Please, make sure to initiate your Pdo object with the charset iso as utf8. This should fix this problem avoiding any re-utf8izing dance.

请确保使用字符集 iso 作为 utf8 启动您的 Pdo 对象。这应该可以解决这个问题,避免任何重新 utf8izing 的舞蹈。

$pdo = new PDO("mysql:host=localhost;dbname=mybase;charset=utf8", 'user', 'password');

回答by M.Bilal Murtaza

you just add in your pdo connection charset=utf8like below line of pdo connection:

您只需添加您的 pdo 连接charset=utf8如下面的 pdo 连接:

$pdo = new PDO("mysql:host=localhost;dbname=mybase;charset=utf8", 'user', 'password');

hope this will help you

希望能帮到你

回答by Fernando Coelho

I know this is kind of an old topic, but for me it was what I needed. I just needed to modify the answer 'jayashan perera'.

我知道这是一个古老的话题,但对我来说这是我需要的。我只需要修改答案'jayashan perera'。

//...code
        $stmt->execute();
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);


        for ($i=0; $i < sizeof($result) ; $i++) { 
            $tempCnpj = $result[$i]['CNPJ'];
            $tempFornecedor = json_encode(html_entity_decode($result[$i]['Nome_fornecedor']),true) ;
            $tempData = $result[$i]['efetivado_data'];
            $tempNota = $result[$i]['valor_nota'];
            $arrResposta[$i] = ["Status"=>"true", "Cnpj"=>"$tempCnpj", "Fornecedor"=>$tempFornecedor, "Data"=>"$tempData", "Nota"=>"$tempNota" ];
        }

        echo json_encode($arrResposta);

And no .js i have use

没有 .js 我用过

obj = JSON.parse(msg); 

回答by jayashan perera

Remove HTML entities before JSON encoding. I used html_entity_decode()in PHP and the problem was solved

在 JSON 编码之前删除 HTML 实体。我html_entity_decode()在PHP中使用,问题解决了

$json = html_entity_decode($source);
$data = json_decode($json,true);