json decode remove the new line

5k Views Asked by At

Find my Json code.

$result  =  { 
        "text_1": 
            [
                { 
                    "text": "Name \nKarSho", 
                    "left": 0, 
                    "right": 0
                }
            ]
    }

I want "text" from this Json in PHP. I used following script,

$json = json_decode($result,true);
if($json && isset($json['text_1']))
{
    $textblock =$json['text_1'][0];
    echo $textblock['text'];
}

It's giving,

Name KarSho

But I want,

Name \nKarSho

What to do?

3

There are 3 best solutions below

4
On BEST ANSWER

Well, to your surpeize, it will give you, Name \nKarSho as output, But when you render that in HTML (In any Browser), You will not see a new line, because more than one spaces and new lines are ignored by browsers, if you go to view source of the browser, you will see a new line there,

If you want your HTML to show the new line, use

echo nl2br($textblock['text']);

So that your new lines will be converted to <br> tag, and you will see that in your HTML output.


Edit:

If you want to see also \n in output (as is), You just want

echo json_encode($textblock['text']);

and to remove the quotes,

echo trim(json_encode($textblock['text']), '"');
0
On
<?php  
header('Content-Type: text/plain'); 
$result  = '{"text_1": [{"text": "Name \nKarSho", "left": 0,"right": 0}]}';
$json = json_decode($result,true);
if($json && isset($json['text_1']))
{
    $textblock =$json['text_1'][0];
    echo $textblock['text'];
}

    ?>

use header function to disply next line

0
On

OP doesn't want a new line, he wants to print \n also.

You can escape \n, for example:

$name = "John \n Will";

echo str_replace("\n", "\\n", $name);

will output:

John \n Will