Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php json_encode not escaping new lines

Tags:

json

php

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.

like image 716
sankar.suda Avatar asked Jun 29 '12 15:06

sankar.suda


People also ask

What does the PHP function json_encode () do?

The json_encode() function is used to encode a value to JSON format.

What does json_encode return?

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.

How check JSON array is empty or not in PHP?

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"; ?>

How can I get JSON encoded data in PHP?

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.


1 Answers

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.

The Solution

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.

like image 60
Madara's Ghost Avatar answered Sep 21 '22 15:09

Madara's Ghost