Skip to content

Instantly share code, notes, and snippets.

@zacscott
Last active December 24, 2015 05:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zacscott/6749225 to your computer and use it in GitHub Desktop.
Save zacscott/6749225 to your computer and use it in GitHub Desktop.
Converts to JSON, in a pretty, human readable format (yet still valid JSON).
<?php
/**
* Converts to JSON, in a 'pretty', human readable format (yet still
* valid JSON).
*
* This code was modified from this GitHub
* <a href="https://gist.github.com/GloryFish/1045396">Gist</a>.
*
* @param string $json The JSON code to prettify.
*/
function prettyJSON($json) {
// parser state
$tabcount = 0;
$result = '';
$inquote = false;
$ignorenext = false;
// parse JSON, generating the reformatted output
for($i = 0; $i < strlen($json); $i++) {
$char = $json[$i];
if ($ignorenext) {
$result .= $char;
$ignorenext = false;
// skip parsing of char (in switch below)
continue;
}
switch($char) {
case ':':
$result .= $char . (!$inquote ? " " : "");
break;
case '{':
if (!$inquote) {
$tabcount++;
$result .= "$char\n" . str_repeat("\t", $tabcount);
} else {
$result .= $char;
}
break;
case '}':
if (!$inquote) {
$tabcount--;
$result = trim($result) . "\n" . str_repeat("\t", $tabcount) . $char;
} else {
$result .= $char;
}
break;
case ',':
if (!$inquote) {
$result .= "$char\n" . str_repeat("\t", $tabcount);
} else {
$result .= $char;
}
break;
case '"':
$inquote = !$inquote;
$result .= $char;
break;
case '\\':
if ($inquote) $ignorenext = true;
$result .= $char;
break;
default:
$result .= $char;
}
}
return $result;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment