php 的json_encode能把数组转换为json格式的字符串。字符串没有缩进,中文会转为unicode编码,例如\u975a\u4ed4。人阅读比较困难。现在这个方法在json_encode的基础上再进行一次美化处理。使人能方便阅读内容。
1. 使用 json_encode 输出
- <?php
- header('content-type:application/json;charset=utf8');
- $arr = array(
- 'status' => true,
- 'errMsg' => '',
- 'member' =>array(
- array(
- 'name' => '李逍遥',
- 'gender' => '男'
- ),
- array(
- 'name' => '赵灵儿',
- 'gender' => '女'
- )
- )
- );
- echo json_encode($arr);
- ?>
- 输出:
- {"status":true,"errMsg":"","member":[{"name":"\u674e\u900d\u9065","gender":"\u7537"},{"name":"\u8d75\u7075\u513f","gender":"\u5973"}]}
php5.4 以后,json_encode增加了JSON_UNESCAPED_UNICODE , JSON_PRETTY_PRINT 等几个常量参数。使显示中文与格式化更方便。
- header('content-type:application/json;charset=utf8');
- $arr = array(
- 'status' => true,
- 'errMsg' => '',
- 'member' =>array(
- array(
- 'name' => '李逍遥',
- 'gender' => '男'
- ),
- array(
- 'name' => '赵灵儿',
- 'gender' => '女'
- )
- )
- );
- echo json_encode($arr, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
header('content-type:application/json;charset=utf8');
$arr = array(
'status' => true,
'errMsg' => '',
'member' =>array(
array(
'name' => '李逍遥',
'gender' => '男'
),
array(
'name' => '赵灵儿',
'gender' => '女'
)
)
);
echo json_encode($arr, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
输出:
- "status": true,
- "errMsg": "",
- "member": [
- {
- "name": "李逍遥",
- "gender": "男"
- },
- {
- "name": "赵灵儿",
- "gender": "女"
- }
- ]
- }