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.
The json_encode() function is used to encode a value to JSON format.
Syntax. The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.
php $json = '{"hello": ["world"], "goodbye": []}'; $decoded = json_decode($json); print "Is hello empty? " . empty($decoded->{'hello'}); print "\n"; print "Is goodbye empty? " . empty($decoded->{'world'}); print "\n"; ?>
To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With