PHP Function for show JSON Raw a bit more readable


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function json_reader($json = '', $indentStr = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", $newLine = "<br/>") {
  2.  
  3. $result = ""; // Resulting string
  4. $indention = ""; // Current indention after newline
  5. $pos = 0; // Indention width
  6. $escaped = false; // FALSE or escape character
  7. $strLen = strlen($json);
  8.  
  9.  
  10. for ($i = 0; $i < $strLen; $i++) {
  11. // Grab the next character in the string
  12. $char = $json[$i];
  13.  
  14. if ($escaped) {
  15. if ($escaped == $char) {
  16. // End of escaped sequence
  17. $escaped = false;
  18. }
  19.  
  20. $result .= $char;
  21. if ($char == "\\" && $i + 1 < $strLen) {
  22. // Next character will NOT end this sequence
  23. $result .= $json[++$i];
  24. }
  25.  
  26. continue;
  27. }
  28.  
  29. if ($char == '"' || $char == "'") {
  30. // Escape this string
  31. $escaped = $char;
  32. $result .= $char;
  33. continue;
  34. }
  35.  
  36. // If this character is the end of an element,
  37. // output a new line and indent the next line
  38. if ($char == '}' || $char == ']') {
  39. $indention = str_repeat($indentStr, --$pos);
  40. $result .= $newLine . $indention;
  41. }
  42.  
  43. // Add the character to the result string
  44. $result .= $char;
  45.  
  46. // If the last character was the beginning of an element,
  47. // output a new line and indent the next line
  48. if ($char == ',' || $char == '{' || $char == '[') {
  49. if ($char == '{' || $char == '[') {
  50. $indention = str_repeat($indentStr, ++$pos);
  51. }
  52. $result .= $newLine . $indention;
  53. }
  54. }
  55.  
  56. return $result;
  57. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.