PHP json字符串,格式化显示
/**
* 格式化
*/
class JsonFormatHelper
{
/**
* json字符串缩进显示
* @param unknown $json
* @return string
*/
public static function jsonIndentShow($jsonStr)
{
echo self::jsonIndentFormat($jsonStr);
} /**
* json字符串缩进
* @param unknown $json
* @return string
*/
public static function jsonIndentFormat($jsonStr)
{
$result = '';
$indentCount = 0;
$strLen = strlen($jsonStr);
$indentStr = ' ';
$newLine = "\r\n";
$isInQuotes = false;
$prevChar = '';
for($i = 0; $i <= $strLen; $i++) {
$char = substr($jsonStr, $i, 1); if($isInQuotes){
$result .= $char;
if(($char=='"' && $prevChar!='\\')){
$isInQuotes = false;
}
}
else{
if(($char=='"' && $prevChar!='\\')){
$isInQuotes = true;
if ($prevChar != ':'){
$result .= $newLine;
for($j = 0; $j < $indentCount; $j++) {
$result .= $indentStr;
}
}
$result .= $char;
}
elseif(($char=='{' || $char=='[')){
if ($prevChar != ':'){
$result .= $newLine;
for($j = 0; $j < $indentCount; $j++) {
$result .= $indentStr;
}
}
$result .= $char;
$indentCount = $indentCount + 1;
}
elseif(($char=='}' || $char==']')){
$indentCount = $indentCount - 1;
$result .= $newLine;
for($j = 0; $j < $indentCount; $j++) {
$result .= $indentStr;
}
$result .= $char;
}
else{
$result .= $char;
}
}
$prevChar = $char;
}
return $result;
}
}