Table Of Contents

m

全干工程师

PHP在JSON转换的时候不转换unicode编码

比如一个数组里面中文值在使用json_encode时候不希望把中文转成\u4f60这种形式,在PHP5.4版本中json_encode增加了一个flag叫JSON_UNESCAPED_UNICODE

$array = array("1" => "PHP code tester Sandbox Online",  
              "foo" => "bar", 5 , 5 => 89009, 
              "case" => "Random Stuff: " . rand(100,999),
              "PHP Version" => phpversion(),
              "你好"
              );
              
echo json_encode($array, JSON_UNESCAPED_UNICODE);

print:

{"1":"PHP code tester Sandbox Online","foo":"bar","2":5,"5":89009,"case":"Random Stuff: 772","PHP Version":"7.1.0","6":"你好"}

不使用JSON_UNESCAPED_UNICODE结果:

{"1":"PHP code tester Sandbox Online","foo":"bar","2":5,"5":89009,"case":"Random Stuff: 173","PHP Version":"7.1.0","6":"\u4f60\u597d"}

留言