JSON中的PHP Unicode [英] PHP Unicode in JSON

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

问题描述

我正在将JSON POST正文发送到我的PHP Web服务,如下所示:

I'm sending a JSON POST body to my PHP web service that looks something like this:

{
    "foo": "☺"
}

当我在PHP中回显主体时,会看到以下内容:

When I echo out the body in the PHP, I see this:

{
    "foo":"\xe2\x98\xba"
}

我还尝试发送等效的\uXXXX:

{
    "foo": "\u263a"
}

更进一步,因为接收到的原始JSON字符串具有"foo":"\\u263a",但是在json_decode之后,该值变成了\xe2\x98\xba.

This got further, in that the raw JSON string received had "foo":"\\u263a", but after json_decode the value turned to \xe2\x98\xba.

当我开始在JSON响应中使用该值时,这会引起问题.我得到:

This is causing problems when I come to use the value in a JSON response. I get:

json_encode(): Invalid UTF-8 sequence in argument

最简单的说,这就是为什么我尝试对字符串进行JSON编码的原因:

At its simplest, this is what happens why I try to JSON encode the string:

> php -r 'echo json_encode("\x98\xba\xe2");'
PHP Warning:  json_encode(): Invalid UTF-8 sequence in argument in Command line code on line 1

我的问题是:如何最好地将这张笑脸从应用程序的一端移到另一端?

My question is: how can I best get this smiley face from one end of my application to the other?

非常感谢您能提供的帮助.

I'd appreciate any help you could offer.

推荐答案

我相信这是json_encode的正确行为.如果您使用以下内容:

I believe this is the correct behavior of json_encode. If you use the following:

<script>
    alert(
     <?php
       $a = "☺";
       echo json_encode($a);
     ?>
    );
</script>

HTML输出将为alert("\u263a");,并且警报将显示为,因为"\u263a"是JavaScript中字符串的正确表示形式.

The HTML output will be alert("\u263a"); and the alert will show since "\u263a" is a correct representation of the string in JavaScript.

使用 JSON_UNESCAPED_UNICODE 常量作为的第二个参数PHP中的json_encode也是一个选项,但仅适用于PHP 5.4.0或更高版本.

Usage of JSON_UNESCAPED_UNICODE constant as the second parameter of json_encode in PHP is also an option, but available only for PHP 5.4.0 or newer.

您打算在哪种情况下使用该值?

In what scenario do you intend to use the value?

php -r'echo json_encode("\ x98 \ xba \ xe2");'

php -r 'echo json_encode("\x98\xba\xe2");'

PHP警告:json_encode():第1行的命令行代码中的参数中的UTF-8序列无效

PHP Warning: json_encode(): Invalid UTF-8 sequence in argument in Command line code on line 1

问题是您使用了错误的字符序列.应该是

The problem is you use a wrong sequence of characters. It should be

echo json_encode("\xe2\x98\xba"); // this works for me

代替

echo json_encode("\x98\xba\xe2"); 

这篇关于JSON中的PHP Unicode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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