json 解码删除新行

json decode remove the new line

找到我的 Json 代码。

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

我想要 PHP 中的 Json "text"。我使用了以下脚本,

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

这是给予,

Name KarSho

但是我想要,

Name \nKarSho

怎么办?

好吧,出乎意料,它会给你 Name \nKarSho 作为输出,但是当你在 HTML 中渲染它时(在任何浏览器中),你不会看到新行,因为多个空格和新行被浏览器忽略,如果你去查看浏览器的源代码,你会在那里看到一个新行,

如果您希望 HTML 显示新行,请使用

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

这样您的新行将被转换为 <br> 标记,您将在 HTML 输出中看到它。


编辑:

如果您还想在输出中看到 \n(按原样),您只需要

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

并删除引号,

echo trim(json_encode($textblock['text']), '"');
<?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'];
}

    ?>

使用表头功能显示下一行

OP不想换行,他还想打印\n

可以转义\n,例如:

$name = "John \n Will";

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

将输出:

John \n Will