5

我正在向我的 PHP Web 服务发送一个 JSON POST 正文,看起来像这样:

{
    "foo": "☺"
}

当我在 PHP 中回显正文时,我看到:

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

我也试过发送\uXXXX等价的:

{
    "foo": "\u263a"
}

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

当我在 JSON 响应中使用该值时,这会导致问题。我得到:

json_encode(): Invalid UTF-8 sequence in argument

简而言之,这就是我尝试对字符串进行 JSON 编码的原因:

> 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

我的问题是:我怎样才能最好地将这个笑脸从我的应用程序的一端带到另一端?

我很感激你能提供的任何帮助。

4

3 回答 3

2
于 2013-06-03T11:49:59.397 回答
2

PHP's json_decode() function behaves correctly given your input case, returning the sequence of UTF-8 bytes (E2 98 BA) that represent the character.

However, Apache HTTPD applies the \x escaping (in function ap_escape_logitem()) before writing the line to the error log (as you did for testing purposes using error_log()). As noted in file server/gen_test_char.c, "all [...] 8-bit chars with the high bit set" are escaped.

于 2013-06-03T12:25:06.253 回答
1

I think when you encode you have to use json_encode({ foo": "☺"}, JSON_UNESCAPED_UNICODE)

Basically json_encode function works only for UTF-8 encoding so before you encode check the encoding of string,like this .

 mb_check_encoding("your string", 'UTF-8') ;

if it returns false then you can convert to utf-8 using

utf8_encode("your string");
于 2013-06-03T11:51:27.527 回答