You could use PHP_EOL for a new line. Where to include new line depends on how you want. In the case below, i need a new line after the last closing square bracket and each curly bracket:
tit1: {
"prop1" : [ "", "", []],
"prop2" : [ "", "", []]
},
tit2: {
"prop1" : [ "", "", []],
"prop2" : [ "", "", []]
}
The function is
$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;
}
\r\n, 2) how do you send that string to your database? did you properly quote / escape the value (or at the very least useaddslashes()) on it?