2013-05-14 09:21
浏览 24

包含utf8字符的PHP utf8_encode [关闭]

Background: A part of my system uses utf8_encode to convert html code to utf8 format before passing it on to json_encode.

Problem: Everything was fine until I entered UTF8 characters(Chinese) into the system. I noticed that the mentioned UTF8 characters were encoded twice and came out garbled.

Sidenote: I have no experience with charset encoding and whatnot until now. Perhaps I don't need to use utf8_encode before json_encode since my database and connections are already set to utf8. Without the Chinese characters in the html code, mb_detect_encoding would return ASCII(not ISO-8859-1). But I couldn't get through json_encode without returning null... thus the use of utf_8 encode which worked until now.

Update: I finally solved the issue by typecasting the html code as string; via (string)$html; before assigning it to json_encode().

Thanks to all who posted here that led me to the final solution.

图片转代码服务由CSDN问答提供 功能建议

背景: 我的系统的一部分使用utf8_encode将html代码转换为utf8格式,然后再将其传递给json_encode。

问题: 在我输入UTF8字符(中文)到系统之前一切正常。 我注意到所提到的UTF8字符被编码了两次并且出现了乱码。

旁注: 我没有使用charset编码的经验,直到现在还没有。 也许我不需要在json_encode之前使用utf8_encode,因为我的数据库和连接已经设置为utf8。 如果没有html代码中的中文字符,mb_detect_encoding将返回ASCII(不是ISO-8859-1)。 但是我无法通过json_encode而不返回null ...因此使用utf_8编码直到现在才有效。

更新: 我终于通过将html代码强制转换为解决了这个问题 串; via(string)$ html; 在将其分配给json_encode()之前。


  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duangou6446 2013-05-14 09:39

    I had similar problem. Maybe this would help: try to use iconv();. I had some problems with Polish characters (ąężćźłóń etc.)  in encodings other that utf8 - when I used json_encode, there was no output. Everything went just fine after using iconv();. The catch is, you have to know source encoding before you proceed. If you don't know encoding, use mb_detect_encoding() as @Lukas suggested. Example:

    $content = iconv('ISO-8859-2','UTF-8', $content);
    echo json_encode(array('content' => $content));
    解决 无用
    打赏 举报

相关推荐 更多相似问题