Skip to content

Instantly share code, notes, and snippets.

@falexandre
Last active August 29, 2015 14:06
Show Gist options
  • Save falexandre/e85587f95494672c6ddc to your computer and use it in GitHub Desktop.
Save falexandre/e85587f95494672c6ddc to your computer and use it in GitHub Desktop.
<?php
function indent_json ($json)
{
$result = '';
$pos = 0;
$strLen = strlen($json);
$indentStr = "\t";
$newLine = "\n";
$prevChar = '';
$outOfQuotes = true;
for ($i=0; $i<=$strLen; $i++):
$char = substr($json, $i, 1);
if ($char == '"' && $prevChar != '\\'):
$outOfQuotes = !$outOfQuotes;
elseif(($char == '}' || $char == ']') && $outOfQuotes):
$result .= $newLine;
$pos --;
for ($j=0; $j<$pos; $j++):
$result .= $indentStr;
endfor;
endif;
$result .= $char;
if (($char == ',' || $char == '{' || $char == '[') && $outOfQuotes):
$result .= $newLine;
if ($char == '{' || $char == '['):
$pos ++;
endif;
for ($j = 0; $j < $pos; $j++):
$result .= $indentStr;
endfor;
endif;
$prevChar = $char;
endfor;
return $result;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment