Debian Stable php-5.4上的Symfony2 JsonResponse utf8编码问题


Symfony2 JsonResponse utf8 encoding issues on Debian Stable php-5.4

我在Debian Stable php5(5.4.39-0+deb7u1)上返回UTF8字符时遇到JsonResponse问题。

我在Debian Testing php5(5.6.6+dfsg-2)上开发了一个应用程序,下面的代码运行起来很有魅力:

$response = new JsonResponse();
$response->headers->set('Content-Type', 'application/json');
$response->setData($data);
return $response;

但在部署到稳定的prod服务器后,我开始为完全相同的DB/Data字符集等获得以下异常:

request.CRITICAL: Uncaught PHP Exception InvalidArgumentException: "Malformed UTF-8 characters, 
possibly incorrectly encoded." at /site/vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/JsonResponse.php
 line 123 {"exception":"[object] (InvalidArgumentException(code: 0): 
Malformed UTF-8 characters, possibly incorrectly encoded. at 
/site/vendor/symfony/symfony/src/Symfony/Component/HttpFoundation/JsonResponse.php:123)"} []

作为$data DO传递的来自DB的响应包含我无法控制的UTF8字符。我只需要展示一下。

我想我遇到了5.4的错误,但我怎么能轻松绕过它呢?我试过了:

    $response = new JsonResponse();
    $response->headers->set('Content-Type', 'application/json');
    $response->setEncodingOptions(JSON_UNESCAPED_UNICODE);
    $response->setData($data);
    return $response;

但我也犯了同样的错误。

想法?

在讨论#symfony通道后,我找到了一个解决方法:

    $response = new Response(json_encode($data, JSON_UNESCAPED_UNICODE));
    $response->headers->set('Content-Type', 'application/json');
    return $response;

欢迎其他不错的解决方案。我认为这个解决方案是一个肮脏的黑客。。。

我认为您没有得到有效的UTF-8字符串。尝试找出为什么存在无效的utf8字节块(http://en.wikipedia.org/wiki/UTF-8#Invalid_byte_sequences)。

您可以使用unpack分析字节:https://stackoverflow.com/a/11466734/4469738