最新消息: 新版网站上线了!!!

php 格式化json函数

  1. <?php 
  2. $arr = array("ret"=>0,"data"=>array('a' => 1, 'b' => "懒人程序"'c' => 3, 'd' => 4, 'e' => 5)); 
  3.  
  4. $json =  json_encode($arr); 
  5.  
  6.  
  7.     /** 
  8.      * Formats a JSON string for pretty printing 
  9.      * 
  10.      * @param string $json The JSON to make pretty 
  11.      * @param bool $html Insert nonbreaking spaces and <br />s for tabs and linebreaks 
  12.      * @return string The prettified output 
  13.      * @author 懒人程序 
  14.      */ 
  15. function _format_json($json$html = false) { 
  16.         $tabcount = 0;  
  17.         $result = '';  
  18.         $inquote = false;  
  19.         $ignorenext = false;  
  20.  
  21.         if ($html) {  
  22.             $tab = "&nbsp;&nbsp;&nbsp;";  
  23.             $newline = "<br/>";  
  24.         } else {  
  25.             $tab = "\t";  
  26.             $newline = "\n";  
  27.         }  
  28.  
  29.         for($i = 0; $i < strlen($json); $i++) {  
  30.             $char = $json[$i];  
  31.  
  32.             if ($ignorenext) {  
  33.                 $result .= $char;  
  34.                 $ignorenext = false;  
  35.             } else {  
  36.                 switch($char) {  
  37.                     case '{':  
  38.                         $tabcount++;  
  39.                         $result .= $char . $newline . str_repeat($tab$tabcount);  
  40.                         break;  
  41.                     case '}':  
  42.                         $tabcount--;  
  43.                         $result = trim($result) . $newline . str_repeat($tab$tabcount) . $char;  
  44.                         break;  
  45.                     case ',':  
  46.                         $result .= $char . $newline . str_repeat($tab$tabcount);  
  47.                         break;  
  48.                     case '"':  
  49.                         $inquote = !$inquote;  
  50.                         $result .= $char;  
  51.                         break;  
  52.                     case '\\':  
  53.                         if ($inquote$ignorenext = true;  
  54.                         $result .= $char;  
  55.                         break;  
  56.                     default:  
  57.                         $result .= $char;  
  58.                 }  
  59.             }  
  60.         }  
  61.  
  62.         return $result;  
  63.     } 
  64. echo _format_json($json); 
  65.  
  66. /* 
  67.  
  68. { 
  69.     "ret": 0, 
  70.     "data": { 
  71.         "a": 1, 
  72.         "b": "\u61d2\u4eba\u7a0b\u5e8f", 
  73.         "c": 3, 
  74.         "d": 4, 
  75.         "e": 5 
  76.     } 
  77. } 
  78.  
  79. **/ 
  80. ?> 

 

转载请注明:谷谷点程序 » php 格式化json函数