×

Welcome to TagMyCode

Please login or create account to add a snippet.
2
0
 
1
Language: PHP
Posted by: Aleksandr Trofimov
Added: Aug 20, 2012 9:21 PM
Modified: Aug 20, 2012 9:22 PM
Views: 1764
Tags: no tags
  1. <?php
  2. function json_pretty($json, $html = false) {
  3.     $out = ''; $nl = "\n"; $cnt = 0; $tab = 4; $len = strlen($json); $space = ' ';
  4.     if($html) {
  5.         $space = '&nbsp;';
  6.         $nl = '<br/>';
  7.     }
  8.     $k = strlen($space)?strlen($space):1;
  9.     for ($i=0; $i<=$len; $i++) {
  10.         $char = substr($json, $i, 1);
  11.         if($char == '}' || $char == ']') {
  12.             $cnt --;
  13.             $out .= $nl . str_pad('', ($tab * $cnt * $k), $space);
  14.         } else if($char == '{' || $char == '[') {
  15.             $cnt ++;
  16.         }
  17.         $out .= $char;
  18.         if($char == ',' || $char == '{' || $char == '[') {
  19.             $out .= $nl . str_pad('', ($tab * $cnt * $k), $space);
  20.         }
  21.         if($char == ':') {
  22.             $out .= ' ';
  23.         }
  24.     }
  25.     return $out;
  26. }
  27. $arr = array('name'=>'John', 'age'=>19, 'address'=>array(array('city'=>'Nashville', 'country'=>'US')));
  28. $json_string = json_encode($arr);
  29. echo json_pretty($json_string, true); // Pass true as the second parameter to get the output in HTML
  30. ?>
Comments disabled