JSON Encoding and decoding of UTF8 characters in P

2019-08-04 00:12发布

When decoding/encoding a utf8 string using json_encode/json_decode I do not get back the string in the original encoding...

$test = '{"c":"limón"}';

echo $test;                           //=> {"c":"limón"}    
echo json_decode($test)->{"c"};       //=> limón
echo json_encode(json_decode($test)); //=> {"c":"lim\u00f3n"}

How can I encode the string back to its original encoding (utf8)?

1条回答
We Are One
2楼-- · 2019-08-04 01:11

The default behavior of json_encode is to escape all Unicode characters. If your PHP is version 5.4.0 or greater, you can pass JSON_UNESCAPED_UNICODE as the second parameter of json_encode to get the behavior you're expecting. There are numerous hacks to get this behavior in earlier versions, including preprocessing your object to encode Unicode characters as HTML entities, then reversing the transformation afterwards.

查看更多
登录 后发表回答