JSON PHP中的UTF8字符的编码和解码 [英] JSON Encoding and decoding of UTF8 characters in PHP

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

问题描述

当使用json_encode / json_decode解码/编码utf8字符串时,我不会回到原始编码中的字符串...

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"}

如何将字符串编码回原始编码(utf8)?

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

推荐答案

json_encode 的默认行为以转义所有Unicode字符。如果您的PHP是5.4.0或更高版本,您可以传递 JSON_UNESCAPED_UNICODE 作为 json_encode 的第二个参数,你期待的行为。有许多黑客在早期版本中遇到此行为,包括预处理您的对象将Unicode字符编码为HTML实体,然后反转变换。

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.

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

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