http://blog.csdn.net/fdipzone/article/details/28766357
php5.4 以后,json_encode增加了JSON_UNESCAPED_UNICODE , JSON_PRETTY_PRINT 等幾個常量參數。使顯示中文與格式化更方便。
多層中文亂碼解決:
<?php
調用:
header('content-type:application/json;charset=utf8');$arr =array( 'status'=>true, 'errMsg'=>'', 'member'=>array( array( 'name'=>'李逍遙', 'gender'=>'男' ), array( 'name'=>'趙靈兒', 'gender'=>'女' ) ));echo jsonFormat($arr);
/** 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); }}?>
新聞熱點
疑難解答
圖片精選