问题json_encode utf-8 [英] Problem json_encode utf-8

查看:157
本文介绍了问题json_encode utf-8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有特殊字符的json_encode函数的问题。

I have a problem with json_encode function with special characters.

例如,我尝试这样:

$string="Svrček";

echo "ENCODING=".mb_detect_encoding($string); //ENCODING=UTF-8

echo "JSON=".json_encode($string); //JSON="Svr\u010dek"

如何正确显示字串, JSON =Svrček?

What can I do to display the string correctly, so JSON="Svrček"?

非常感谢。

推荐答案

json_encode()实际上并不输出 JSON 。它输出一个javascript字符串。 (当你给它一个对象或一个数组进行编码时,它输出JSON。)这很好,因为一个javascript字符串是你想要的。

json_encode() is not actually outputting JSON there. It's outputting a javascript string. (It outputs JSON when you give it an object or an array to encode.) That's fine, as a javascript string is what you want. I'm just being strict about terminology.

在javascript(和JSON)中,č可能会被转义为 \u010 。两者是等价的。因此, json_encode()是做什么的。但是,如果传输是安全的Unicode编码(通常是UTF-8),也没有必要。如果你想关闭转义,你可以这样做: json_encode('Svrček',JSON_UNESCAPED_UNICODE)。请注意,在PHP 5.4.0中引入了标志 JSON_UNESCAPED_UNICODE ,并且在早期版本中不可用。

In javascript (and in JSON), č may be escaped as \u010. The two are equivalent. So there's nothing wrong with what json_encode() is doing. However, if the transfer is safely in a Unicode encoding (UTF-8, usually), there's no need for it either. If you want to turn off the escaping, you can do so thus: json_encode('Svrček', JSON_UNESCAPED_UNICODE). Note that the flag JSON_UNESCAPED_UNICODE was introduced in PHP 5.4.0, and is unavailable in earlier versions.

方式,与@onteria_所说的相反, JSON 使用UTF-8

By the way, contrary to what @onteria_ says, JSON does use UTF-8:


JSON文本的字符编码始终是Unicode。 UTF-8是唯一有意义的编码,但也允许使用UTF-16和UTF-32。

The character encoding of JSON text is always Unicode. UTF-8 is the only encoding that makes sense on the wire, but UTF-16 and UTF-32 are also permitted.

这篇关于问题json_encode utf-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆