1 <?php
2 // json_encode() 保持中文方法详解
3
4 $arr['city'] = '北京';
5 $arr['name'] = 'weilong';
6
7 // 直接输出
8 // Res: {"city":"\u5317\u4eac","name":"weilong"}
9 echo json_encode($arr), "\n";
10
11 #### 1. 加参数,PHP版本>=5.4
12 // Res: {"city":"北京","name":"weilong"}
13 echo json_encode($arr, JSON_UNESCAPED_UNICODE), "\n"; // php >= 5.4
14
15 #### 2. 正则替换,json_encode后,正则将编码替换成中文
16 // Res: {"city":"北京","name":"weilong"}
17 echo preg_replace("#\\\u([0-9a-f]{4})#ie", "iconv('UCS-2BE', 'UTF-8', pack('H4', '\\1'))", json_encode($arr)), "\n"; // PHP 5.5 /e修饰符被弃用
18 echo preg_replace_callback("/\\\u([0-9a-f]{4})/i", function($match) { // php >= 5.3 都可以
19 return json_decode("\"{$match[0]}\"", true);
20 }, json_encode($arr)), "\n";
21
22 #### 3. urldecode()、urlencode()函数,不推荐
23 // Res1: null, Res2: {"city":"北京","name":"weilong"}
24 echo urldecode(json_encode(urlencode($arr))), "\n";
25 $arr['city'] = urlencode($arr['city']); // urlencode()参数必须是string
26 echo urldecode(json_encode($arr)), "\n";
27
28
29 // 另外注意json_decode()参数区别。
30 $arr['city'] = '北京';
31 $arr['name'] = 'weilong';
32 $str = json_encode($arr);
33 $str2 = json_decode($str);
34 $str3 = json_decode($str, true);
35
36 print_r($str2); // object
37 /* Res:
38 stdClass Object
39 (
40 [city] => 北京
41 [name] => weilong
42 ) */
43
44 print_r($str3); // array
45 /* Res:
46 Array
47 (
48 [city] => 北京
49 [name] => weilong
50 )
51 */