json_encode()非utf-8字符串?

Jos*_*osh 25 php encoding json ansi utf-8

所以我有一个字符串数组,所有字符串都使用系统默认的ANSI编码,并从sql数据库中提取.因此,有256种不同的可能字符字节值(单字节编码).有没有办法让json_encode()工作并显示这些字符而不必在我的所有字符串上使用utf8_encode()并最终得到像"\ u0082"这样的东西?

或者这是json的标准?

hak*_*kre 33

有没有办法让json_encode()工作并显示这些字符而不必在我的所有字符串上使用utf8_encode()并最终得到像"\ u0082"这样的东西?

如果你有一个ANSI编码的字符串,使用utf8_encode()错误的函数来处理这个.您需要先将其正确地从ANSI转换为UTF-8.这肯定会减少像\u0082json输出那样的Unicode转义序列的数量,但从技术上讲这些序列对json有效,你不能害怕它们.

使用PHP将ANSI转换为UTF-8

json_encode适用于UTF-8编码字符串.如果需要从编码字符串成功创建有效,则需要先将其重新编码/转换.然后将按照记录的方式工作.jsonANSIUTF-8json_encode

要转换编码ANSI(更准确地说,我假设您有一个Windows-1252受欢迎但被错误地称为编码的字符串ANSI),UTF-8您可以使用该mb_convert_encoding()函数:

$str = mb_convert_encoding($str, "UTF-8", "Windows-1252");
Run Code Online (Sandbox Code Playgroud)

PHP中可以转换字符串的编码/字符集的另一个函数是iconv基于libiconv调用的.你也可以使用它:

$str = iconv("CP1252", "UTF-8", $str);
Run Code Online (Sandbox Code Playgroud)

关于utf8_encode()的注释

utf8_encode()只会起作用Latin-1,而不是起作用ANSI.因此,当您通过该函数运行时,您将销毁该字符串中的部分字符.


相关:什么是ANSI格式?


有关返回的更精细控制json_encode(),请参阅预定义常量列表(取决于PHP版本,包括PHP 5.4,某些常量仍未记录,仅在源代码中可用到目前为止).

迭代地更改数组的编码(PDO注释)

正如您在评论中写道,将函数应用于数组时遇到问题,这里有一些代码示例.它总是需要使用前更改编码json_encode.这只是一个标准的数组操作,对于更简单pdo::fetch()foreach迭代情况:

while($row = $q->fetch(PDO::FETCH_ASSOC))
{
  foreach($row as &$value)
  {
    $value = mb_convert_encoding($value, "UTF-8", "Windows-1252");
  }
  unset($value); # safety: remove reference
  $items[] = array_map('utf8_encode', $row );
}
Run Code Online (Sandbox Code Playgroud)


And*_*ore 10

JSON标准ENFORCES Unicode编码.来自RFC4627:

3.  Encoding

   JSON text SHALL be encoded in Unicode.  The default encoding is
   UTF-8.

   Since the first two characters of a JSON text will always be ASCII
   characters [RFC0020], it is possible to determine whether an octet
   stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking
   at the pattern of nulls in the first four octets.

           00 00 00 xx  UTF-32BE
           00 xx 00 xx  UTF-16BE
           xx 00 00 00  UTF-32LE
           xx 00 xx 00  UTF-16LE
           xx xx xx xx  UTF-8
Run Code Online (Sandbox Code Playgroud)

因此,从最严格的意义上讲,ANSI编码的JSON不是有效的JSON; 这就是PHP在使用时强制执行unicode编码的原因json_encode().

至于"默认ANSI",我很确定您的字符串是在Windows-1252中编码的.它被错误地称为ANSI.


Jen*_*yok 6

<?php
$array = array('first word' => array('?????','?????????'),'second word' => '?????????','last word' => '?????????');
echo json_encode($array);
/*
return {"first word":["\u0421\u043b\u043e\u0432\u043e","\u041a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430"],"second word":"\u041a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430","last word":"\u041a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430"}
*/
echo json_encode($array,256);
/*
return {"first word":["?????","?????????"],"second word":"?????????","last word":"?????????"}
*/
?>
Run Code Online (Sandbox Code Playgroud)

JSON_UNESCAPED_UNICODE(整数)按字面意义编码多字节Unicode字符(默认为转义为\ uXXXX)。自PHP 5.4.0起可用。

http://php.net/manual/en/json.constants.php#constant.json-unescaped-unicode