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;
}