Ant*_*lqk 10 php utf-8 symfony jsonresponse
当我返回UTF8字符时,我在Debian Stable php5(5.4.39-0 + deb7u1)上遇到JsonResponse问题.
我在Debian Testing php5(5.6.6 + dfsg-2)上开发了一个应用程序,下面的代码就像一个魅力:
$response = new JsonResponse();
$response->headers->set('Content-Type', 'application/json');
$response->setData($data);
return $response;
Run Code Online (Sandbox Code Playgroud)
但是在部署到稳定的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)"} []
Run Code Online (Sandbox Code Playgroud)
作为$ data DO传递的DB的响应包含我无法控制的UTF8字符.我只需要显示它们.
我想我遇到了5.4的bug,但是我怎么能轻松地走动呢?我试过了:
$response = new JsonResponse();
$response->headers->set('Content-Type', 'application/json');
$response->setEncodingOptions(JSON_UNESCAPED_UNICODE);
$response->setData($data);
return $response;
Run Code Online (Sandbox Code Playgroud)
但我得到了同样的错误.
想法?
Ant*_*lqk 10
在讨论#symfony频道后,我发现了一个解决方法:
$response = new Response(json_encode($data, JSON_UNESCAPED_UNICODE));
$response->headers->set('Content-Type', 'application/json');
return $response;
Run Code Online (Sandbox Code Playgroud)
欢迎其他好的解决方案.我认为这个解决方案是一个肮脏的黑客......