3

我的 php 脚本为 JSON 提供了这个字符串(例如):

{"时间":"0:38:01","kto":"\u00d3\u00e1\u00e8\u00e2\u00f6\u00e0 \u00c3\u00e5\u00ed\u00e5\u00f0\u00e0\u00eb\u00ee\u00e2", "混乱":"\u00c5\u00e4\u00e8\u00ed\u00fb\u00e9: *mm"}

jQuery 代码通过 JSON 获取这个字符串:

$.getJSON('chat_ajax.php?q=1',
    function(result) {
    alert('Time ' + result.time + ' Kto' + result.kto + ' Mess' + result.mess);
    });

浏览器展示:

0:38:01 Óáèâöà Ãåíåðàëîâ
Åäèíûé: *mm

如何将此字符串解码为西里尔字母?

尝试使用:

<META http-equiv="content-type" content="text/html; charset=windows-1251">

但没有任何改变

PHP代码:

 $res1=mysqli_query($dbc, "SELECT * FROM chat ORDER BY id DESC LIMIT 1");
   while ($row1=mysqli_fetch_array($res1)) {
       $rawArray=array('time' => @date("G:i:s", ($row1['time'] + $plus)), 'kto' => $row1[kto], 'mess' => $row1[mess]);
       $encodedArray = array_map(utf8_encode, $rawArray); 
       echo json_encode($encodedArray); 

PHP 版本 5.3.19

4

2 回答 2

2

\uXXXX代表unicode字符,在 unicode00d3中是Ó等等。Unicode 字符是明确的,因此页面的字符编码将被忽略。您可以使用正确的 unicode(即\u0443for У)或编写脚本,以便它输出 Windows-1251 中的真实字符,而不是 unicode 序列。

更新

我从您的评论中看到您从 MySQL 获取此数据并用于json_encode()输出它。json_encode仅适用于 UTF-8 编码的数据(并且d3也是ÓUTF-8,这就是为什么你得到错误的 unicode 序列的原因)。

因此,您必须先将所有数据从 Windows-1251 转换为 UTF-8 然后再将其传递给json_encode,然后其他一切都会正常工作。

转换:

$utf8Array = array_map(function($in) {
    return iconv('Windows-1251', 'UTF-8', $in);
}, $rawArray);

utf8_encode将不起作用,因为它仅对 ISO-8859-1 编码的输入有用。

于 2013-02-24T21:26:15.630 回答
1

在 MySQL BDD 中存储 json 数据时我遇到了类似的问题:这解决了问题:

json_encode($json_data, JSON_UNESCAPED_UNICODE) ;

于 2018-04-30T14:31:56.757 回答