Skip to content

Instantly share code, notes, and snippets.

@guimadaleno
Created September 1, 2022 15:21
Show Gist options
  • Save guimadaleno/1e7c66b9373800cfd15e1ec055f3856a to your computer and use it in GitHub Desktop.
Save guimadaleno/1e7c66b9373800cfd15e1ec055f3856a to your computer and use it in GitHub Desktop.
Indent JSON string
<?php
/**
* Indent JSON strings
* @param string $str
* @return string json
*/
function indent_json ($str)
{
$output = "";
$pos = 0;
$lgh = strlen($str);
$istr = "\t";
$nl = "\n";
$pc = '';
$ooq = true;
for ($i=0; $i<=$lgh; $i++):
$char = substr($str, $i, 1);
if ($char == '"' && $pc != '\\'):
$ooq = !$ooq;
elseif (($char == '}' || $char == ']') && $ooq):
$output .= $nl;
$pos --;
for ($j=0; $j<$pos; $j++)
$output .= $istr;
endif;
$output .= $char;
if (($char == ',' || $char == '{' || $char == '[') && $ooq):
$output .= $nl;
if ($char == '{' || $char == '[')
$pos ++;
for ($j = 0; $j < $pos; $j++)
$output .= $istr;
endif;
$pc = $char;
endfor;
return $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment