<?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); ?>
(推荐学习:PHP视频教程)
输出:
{"status":true,"errMsg":"","member":[{"name":"\u674e","gender":"\u7537"},{"name":"\u8d75","gender":"\u5973"}]}
<?php /** Json数据格式化 * @param Mixed $data 数据 * @param String $indent 缩进字符,默认4个空格 * @return JSON */ function jsonFormat($data, $indent=null){ // 对数组中每个元素递归进行urlencode操作,保护中文字符 array_walk_recursive($data, 'jsonFormatProtect'); // json encode $data = json_encode($data); // 将urlencode的内容进行urldecode $data = urldecode($data); // 缩进处理 $ret = ''; $pos = 0; $length = strlen($data); $indent = isset($indent)? $indent : ' '; $newline = "\n"; $prevchar = ''; $outofquotes = true; for($i=0; $i<=$length; $i++){ $char = substr($data, $i, 1); if($char=='"' && $prevchar!='\\'){ $outofquotes = !$outofquotes; }elseif(($char=='}' || $char==']') && $outofquotes){ $ret .= $newline; $pos --; for($j=0; $j<$pos; $j++){ $ret .= $indent; } } $ret .= $char; if(($char==',' || $char=='{' || $char=='[') && $outofquotes){ $ret .= $newline; if($char=='{' || $char=='['){ $pos ++; } for($j=0; $j<$pos; $j++){ $ret .= $indent; } } $prevchar = $char; } return $ret; } /** 将数组元素进行urlencode * @param String $val */ function jsonFormatProtect(&$val){ if($val!==true && $val!==false && $val!==null){ $val = urlencode($val); } } header('content-type:application/json;charset=utf8'); $arr = array( 'status' => true, 'errMsg' => '', 'member' =>array( array( 'name' => '李', 'gender' => '男' ), array( 'name' => '赵', 'gender' => '女' ) ) ); echo jsonFormat($arr); ?>
输出:
{ "status":true, "errMsg":"", "member":[ { "name":"李", "gender":"男" }, { "name":"赵", "gender":"女" } ] }
<?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, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
输出:
{ "status": true, "errMsg": "", "member": [ { "name": "李", "gender": "男" }, { "name": "赵", "gender": "女" } ] }
以上がphp JSONデータを整形(整形)する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。