在接口返回数据中,我们经常会返回json或者xml格式,php的json序列化函数json_encode非常好用,但是默认会把中文编码为ASCII码(注意,很多人认为这是乱码,其实不是),尤其在调试接口时,看到一大串的ASCII码,一脸懵逼,不知是对是错:
代码:
<?php
class A
{
public $num;
public $name; function __construct($_num,$_name)
{
$this->num=$_num;
$this->name=$_name;
}
} $class=new A('A001','张三'); //json_encode序列化
$json=json_encode($class);
echo $json;
结果:
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAASgAAAAiCAIAAABjidOcAAACk0lEQVR4nO2WS3LEIAxEuf95UjlYLkA2qSkCUlvCAvnTr7wYYyEaQcOUH0LIdsr31zcfPnw2P6USQrZD4xGSAI1HSAI0HiEJ0HiEJEDjEZIAjUdIAjQeIQnQeIQkQOMRksCx8UoppZT2tfsRLMiZf7WeqHGp89mMdeuM08cb03W5cNJpvPlX64ka99Y6r+bAq+mpsM6aWrfxcLqTBB7P6oSVLQjal+pcSohOr+YyAAK0li5YFDmBva9rn8zsw8PhLdlDiN3NLsNoG85b5Qmd69hwiuE8h18/twQOwDEuYSdLgQ8m+z6s3hvvRhyelMZFvW8FAllkPLHFsi4TiyKa3KLwpPlvbzz7cVUNR2l9vfFc9azOP2murxvWxXX55xvPqPKzy9u17NZ1DGsxTuBJxtPq1n4d66nVzVvM6qxnlcoirm9tig8mpY3e5cQCjHoqXGuxmOJA0xtDnulEnzHGOMnDH1GImecKGq6tzRxStz2Cx7RAJ1hZLG/aeFiPKz8YSJwjRguLMZ74mmu8qJNsqfHwazcFYLyOLMETvc7kN8YD44l1s6wLngiW/dc+1w0rM7YvMl7gCReuzTiQdsqKP9Yp7FhqPK+v7HqMBjsv2BX2cOO59FheA4mq2zbjdWMF1tPSeBhzMt6VB7QbwzYZTzxpXMZrM8zpASMCJfZtbVfo0uA1nr1KE44F17K27iCD2GJZL5ceS7xx3ImrYpXxxutbey3/qU11Ao2H9YA8Y/soOEShRWfRqVLdXDon1La9tFngso+T0trFXif1VKVEoG6g0VU3LTh4P72cNxTqanO8mp4PB0fGTikP5j3H09WmeTU9Rm4pmpC7Q+MRkgCNR0gCNB4hCdB4hCRA4xGSAI1HSAK/oSrqNnK7Z9cAAAAASUVORK5CYII=" alt="" />
是不是看着很不爽,
解决办法也很简单,网上找的,PHP5.4版本,已经给Json新增了一个选项: JSON_UNESCAPED_UNICODE。加上这个选项后,就不会自动把中文编码了。
试一下:
class A
{
public $num;
public $name; function __construct($_num,$_name)
{
$this->num=$_num;
$this->name=$_name;
}
} $class=new A('A001','张三'); //json_encode序列化
$json=json_encode($class,JSON_UNESCAPED_UNICODE);//加上JSON_UNESCAPED_UNICODE
echo $json;
结果:
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAO4AAAAgCAIAAACabtOxAAAB+klEQVR4nO2WQRaDIAxEuf+l6c5nDYEJJKhx/qq1NhniFy2VkBSUuwMQ4gNVJkmgyiQJVJkkgSqTJFBlkgSqTJJAlUkSqDIxUMpzheklK6Wcox+fg9ZjrR+dx6vvS3OWf5qlXFYki1/EQ+sMG1yqz7UZ5zDWj87j1TdHTlDlggH2tY7LoPJcAzSH31anVdAuaud4aM5QfHM2f3VZ0cR1VEsNe/T7uRA0d+Qv2kUybU5zOeNwzylPiPZ4ogW6K7+I4aMKf1zGBHwN8q3geBnY0912vlehOLQXAO3kCjv6TZXxea4/9FfwURmpcnlhP/shH9b1/xbXnuD9RuDJMv+jVNbmdv5VzlObm3WYdVblZox+nukr3gwwPnmlilxG87/yuHbmOs3KwzzIV0e85hYdWBZs9g3C7P1KIasie1RubhWmnEHZwEZyCR2VV/Y8JOcwSRyfVlnT90Uq93fr/q4cB1VWj29Q2ZQH+eqI19xuVHlD98epjDwoh13AVSG7HagRmM2a0JTBqjI+JbMl2M3vyz6V5VuU9rX8U0/TdFS5n6dTRx6XgV0SIjmLTm3NzZRzIu3xl/OHy1SHyZtrwZuiIfu1rOU+S8pBNcWVK3Vf+5x4CS/AZnLf8EU8r+5KMuS5yQgxQZVJEqgySQJVJkmgyiQJVJkkgSqTJPwAVLo5VrR8jfwAAAAASUVORK5CYII=" alt="" />