You can use PHP_EOL for a new line. Where to include a new line depends on how you want. In the following case, I need a new line after the last closing square bracket and each curly brace:
tit1: { "prop1" : [ "", "", []], "prop2" : [ "", "", []] }, tit2: { "prop1" : [ "", "", []], "prop2" : [ "", "", []] }
Function
$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; }
source share