Created
September 1, 2022 15:21
-
-
Save guimadaleno/1e7c66b9373800cfd15e1ec055f3856a to your computer and use it in GitHub Desktop.
Indent JSON string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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