<?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資料格式化(美化)的方法的詳細內容,更多請關注TW511.COM其它相關文章!