【问题标题】:json_encode preserve line breaks in given textjson_encode 保留给定文本中的换行符
【发布时间】:2018-03-05 21:21:21
【问题描述】:

给定一个从 sql 查询返回的数据集,其中一些字段是“文本”类型并且可能包含任意空格,我需要json_encode它。

$dataset=$stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($dataset);

这可能会以类似的方式结束

[
{
 "field1":"this one is ok, \"double quotes\" are escaped automatically",
 "field2":"But line breaks are not
and so they ruin json"
}
]

我无法在 sql 端更改文本(无论是在表中还是在查询中),我需要在 php 端将换行符替换为 \n 序列。 这是否意味着我不能使用股票json_encode?它转义双引号但不转义 - wtf? 我不能只将换行符替换为空格 - 我需要保留它们(如\n)。 我无法将所有换行符替换为 \n,因为这会影响 json 括号后、字符串之外的换行符。

【问题讨论】:

  • 没有发生,3v4l.org/t7Ub2
  • 您应该使用var_dump() 而不是回显来查看您真正拥有的东西。并且始终检查实际输出,而不是您在浏览器中看到的内容。
  • 明白了!一定是 IIS 的 php 的问题(请不要问我为什么在 IIS 上使用 php)。在 Apache 上它工作正常。谢谢指出!
  • 请不要将解决方案添加到您的问题中。如果您找到了最适合您的解决方案,那么您可以在下面接受它或回答您自己的问题。本网站鼓励其他用户提供多种解决方案,因为最适合您的解决方案可能不适用于其他用户。您的问题已回滚到之前的状态。欲了解更多信息,请访问help center

标签: php json pdo newline


【解决方案1】:

使用PHP_EOLstr_replace

<?php
$array = [
    'field1' => 'this one is ok, "double quotes" are escaped automatically',
    'field2' => 'But line breaks are not
and so they ruin json'
];

$new_json = str_replace(PHP_EOL,"\n",json_encode($array));
echo $new_json;
//output: {"field1":"this one is ok, \"double quotes\" are escaped automatically","field2":"But line breaks are not\nand so they ruin json"}

demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    • 2020-05-03
    相关资源
    最近更新 更多