问题 json_encode utf-8

Problem json_encode utf-8(问题 json_encode utf-8)
本文介绍了问题 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="Svru010dek"

我该怎么做才能正确显示字符串,所以 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.

在 javascript(和 JSON)中,č 可以转义为 u010d.两者是等价的.所以 json_encode() 所做的没有错.它应该可以正常工作.如果这实际上给您带来了任何形式的问题,我会感到非常惊讶.但是,如果传输安全地采用 Unicode 编码(通常为 UTF-8)†,则也不需要它.如果你想关闭转义,你可以这样做:json_encode('Svrček', JSON_UNESCAPED_UNICODE).请注意,标志 JSON_UNESCAPED_UNICODE 是在 PHP 5.4.0 中引入的,在早期版本中不可用.

In javascript (and in JSON), č may be escaped as u010d. The two are equivalent. So there’s nothing wrong with what json_encode() is doing. It should work fine. I’d be very surprised if this is actually causing you any form of problem. 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.

<小时>

* 或者,至少,它没有输出 RFC 4627 中定义的 JSON.但是,还有 JSON 的其他定义,允许标量值.


* Or, at least, it's not outputting JSON as defined in RFC 4627. However, there are other definitions of JSON, by which scalar values are allowed.

† JSON 可以是 UTF-8、UTF-16LE、UTF-16BE、UFT-32LE 或 UTF-32BE.

† JSON may be in UTF-8, UTF-16LE, UTF-16BE, UFT-32LE, or UTF-32BE.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)