1 <?php 2 $testJSON=array(\'name\'=>\'中文字符串\',\'value\'=>\'test\'); 3 echo json_encode($testJSON); 4 ?> 5 6 查看输出结果为: 7 {“name”:”\u4e2d\u6587\u5b57\u7b26\u4e32″,”value”:”test”} 8 可见即使用UTF8编码的字符,使用json_encode也出现了中文乱码。解决办法是在使用json_encode之前把字符用函数urlencode()处理一下,然后再json_encode,输出结果的时候在用函数urldecode()转回来。具体如下: 9 10 11 <?php 12 $testJSON=array(\'name\'=>\'中文字符串\',\'value\'=>\'test\'); 13 //echo json_encode($testJSON); 14 foreach ( $testJSON as $key => $value ) { 15 $testJSON[$key] = urlencode ( $value ); 16 } 17 echo urldecode ( json_encode ( $testJSON ) ); 18 ?> 19 20 21 查看输出结果为: 22 23 24 25 {“name”:”中文字符串”,”value”:”test”}
json_decode() 的例子
1 <?php 2 $json = \'{"a":1,"b":2,"c":3,"d":4,"e":5}\'; 3 var_dump(json_decode($json)); 4 var_dump(json_decode($json, true)); 5 ?> 6 7 8 object(stdClass)#1 (5) { 9 ["a"] => int(1) 10 ["b"] => int(2) 11 ["c"] => int(3) 12 ["d"] => int(4) 13 ["e"] => int(5) 14 } 15 16 array(5) { 17 ["a"] => int(1) 18 ["b"] => int(2) 19 ["c"] => int(3) 20 ["d"] => int(4) 21 ["e"] => int(5) 22 }