给定从sql查询返回的数据集,其中一些字段的类型为“text”并且可能包含任意空格,我需要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括号之后的换行符。
使用PHP_EOL
和str_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"}