Reputation: 1147
I am facing some issue with json_encode.
when i json_encode an array having new lines it is not escaping new lines instead it's removing \ and keeping n.
ex: $array = array('name'=> "some text \n\r text");
$results = json_encode($array);
it is saving some text nr text
in database .
i am using php 5.3.8
.
edit:
This is my original code i am using
$attr = array();
for($i=0; $i < count($_POST['key']); $i++){
$attr[$_POST['key'][$i]] = $_POST['value'][$i];
}
echo json_encode(array('custom' => $attr));
these POST
values getting from form.
Upvotes: 16
Views: 52911
Reputation: 2253
I've found that the simplest solution is to use JSON_UNESCAPED_UNICODE
(along with other flags, if you need them). You can learn more about these flags in the documentation
Regarding the original issue:
<?php
$tmp = array();
$tmp[1] = "test";
$tmp["ok"] = "this
seems to be
a
multiline
nightmare,
but
we
can manage it";
$conv = json_encode($tmp,JSON_UNESCAPED_UNICODE);
echo $conv;
?>
which outputs
{"1":"test","ok":"this\r\nseems to be\r\na\r\nmultiline\r\nnightmare,\r\nbut\r\nwe\r\ncan manage it"}
Upvotes: 0
Reputation:
You could use JSON_PRETTY_PRINT
as described in the PHP manual.
https://www.php.net/manual/function.json-encode.php
Upvotes: 3
Reputation: 371
I use this command to clean the backslashes.
$info = file_get_contents('my_file.txt');
**$info = str_replace(array("r\n","\n", "\r"), "", $info);**
$info = json_decode($info);
Upvotes: 0
Reputation: 969
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;
}
Upvotes: 0
Reputation: 174967
Newlines are not valid characters inside of JSON strings. That's the expected behavior:
char
any Unicode character except " or \ or control-character
- \"
- \
- /
- \b
- \f
- \n
- \r
- \t
- \u four-hex-digits
JSON escapes those control characters into those in the list.
So now we have '\n'
(literally a backslash followed by 'n'), which, if not escaped properly, will be saved in the database as n
. And that is the problem you're experiencing.
Use prepared statements to properly escape any and all slashes in the strings you're storing in your database. That will save them as '\n'
, which you can convert to "\n"
when you retrieve your data.
Upvotes: 10
Reputation: 1147
I figured out this issue. it is not in json_encode problem. it is an error while saving to database.
The problem is magic_quotes_gpc enabled in server. in my application if magic_quotes enabled i am striping the slashes.
i disabled magic_quotes_gpc. working fine now.
Thanks for every body.
Upvotes: 0
Reputation: 14237
You could manually escape them:
$array = array('name'=> "some text \n\r text");
$results = json_encode(array_filter($array, function($arr) use ($array){
return preg_replace('~\\[nrtfd]~', '\\\\$1', $arr);
}));
print_r($results);
You could extend your own json_encode function, and replace your uses of json_encode
to my_json_encode
:
function my_json_encode($json){
$results = json_encode(array_filter($json, function($arr) use ($array){
return preg_replace('~\\[nrtfd]~', '\\\\$1', $arr);
}));
return $results;
}
print_r($results);
FYI, the above returns: {"name":"some text \n\r text"}
instead of {"name":"some text nr text"}
Upvotes: 3
Reputation: 5607
I don't believe json_encode is your problem. My guess is your database is interpreting \ as the escape character, so it simply strips them out.
To combat that, simply escape the escape characters using addslashes:
$results=addslashes($results);
Upvotes: 10