你可以用PHP_EOL
换新线。在哪里包含新行取决于您想要的方式。在下面的情况下,我需要在最后一个右方括号和每个大括号之后换行:
tit1: {
"prop1" : [ "", "", []],
"prop2" : [ "", "", []]
},
tit2: {
"prop1" : [ "", "", []],
"prop2" : [ "", "", []]
}
功能是
$jsonDataTxt = $this->own_format_json($jsonData);
file_put_contents("C:/Users/mm/Documents/Data.json", $jsonDataTxt);
function own_format_json($json, $html = false) {
$tabcount = 0;
$result = '';
$bnew = 0;
$brack=0;
$tab = "\t";
$newline = PHP_EOL;
for($i = 0; $i < strlen($json); $i++) {
$char = $json[$i];
if($char!==',' && $bnew===1) { $bnew=0; $result.= $newline; } //insert new line after ], which is not proceeded by ,
switch($char) {
case '{':
$tabcount++;
$result .= $char . $newline . str_repeat($tab, $tabcount);
break;
case '}':
$tabcount--;
$result = trim($result) . $newline . str_repeat($tab, $tabcount) . $char . $newline;
break;
case '[':
$brack++;
$result .= $char;// . $newline . str_repeat($tab, $tabcount);
break;
case ']':
$brack--;
$result .= $char;// . $newline . str_repeat($tab, $tabcount);
if($brack===0) { $bnew=1; }
//echo "<br><br> case ] char=".$char.', brack='.$brack. ", bnew=".$bnew.", result=".$result ;
break;
case ',':
$result .= $char;// . $newline . str_repeat($tab, $tabcount);
if($bnew===1) { $bnew=0; $result.= $newline; } //insert new line after ],
break;
case '"':
$result .= $char;
break;
default:
$result .= $char;
}
}
return $result;
}