php json_encode 不转义新行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11264631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:08:00  来源:igfitidea点击:

php json_encode not escaping new lines

phpjson

提问by sankar.suda

I am facing some issue with json_encode.

我正面临 json_encode 的一些问题。

when i json_encode an array having new lines it is not escaping new lines instead it's removing \ and keeping n.

当我对具有新行的数组进行 json_encode 时,它​​不会转义新行,而是删除 \ 并保留 n。

ex: $array = array('name'=> "some text \n\r text");
$results = json_encode($array);

it is saving some text nr textin database .

它保存some text nr text在数据库中。

i am using php 5.3.8.

我正在使用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 POSTvalues getting from form.

这些POST值来自形式。

采纳答案by sankar.suda

I figured out this issue. it is not in json_encode problem. it is an error while saving to database.

我想通了这个问题。它不在 json_encode 问题中。保存到数据库时出错。

The problem is magic_quotes_gpcenabled in server. in my application if magic_quotes enabled i am striping the slashes.

问题是在服务器中启用了magic_quotes_gpc。在我的应用程序中,如果启用了 magic_quotes,我将删除斜杠。

i disabled magic_quotes_gpc. working fine now.

我禁用了magic_quotes_gpc。现在工作正常。

Thanks for every body.

感谢每一个身体。

回答by Madara's Ghost

Newlines are not valid characters inside of JSON strings. That's the expected behavior:

换行符不是 JSON 字符串中的有效字符。这是预期的行为:

char

any Unicode character except " or \ or control-character

  • \"
  • \
  • /
  • \b
  • \f
  • \n
  • \r
  • \t
  • \u four-hex-digits

字符

任何 Unicode 字符,除了 " 或 \ 或控制字符

  • \"
  • \
  • /
  • \b
  • \F
  • \n
  • \r
  • \t
  • \u 四位十六进制数字

JSON escapes those control characters into those in the list.

JSON 将这些控制字符转义为列表中的字符。

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 thatis the problem you're experiencing.

所以现在我们有了'\n'(字面意思是一个反斜杠后跟“n”),如果没有正确转义,它将在数据库中保存为n. 而就是你所遇到的问题。

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.

使用准备好的语句正确转义您存储在数据库中的字符串中的任何和所有斜杠。这会将它们保存为'\n',您可以"\n"在检索数据时将其转换为。

回答by Sean Johnson

I don't believe json_encode is your problem. My guess is your database is interpreting \ as the escape character, so it simply strips them out.

我不相信 json_encode 是你的问题。我的猜测是您的数据库将 \ 解释为转义字符,因此它只是将它们去掉。

To combat that, simply escape the escape characters using addslashes:

为了解决这个问题,只需使用addslashes转义转义字符:

$results=addslashes($results);

回答by Mike Mackintosh

You could manually escape them:

您可以手动转义它们:

$array = array('name'=> "some text \n\r text");

$results = json_encode(array_filter($array, function($arr) use ($array){
        return preg_replace('~\[nrtfd]~', '\\', $arr);
}));

print_r($results);

You could extend your own json_encode function, and replace your uses of json_encodeto my_json_encode:

您可以扩展您自己的 json_encode 函数,并替换您对json_encodeto的使用my_json_encode

function my_json_encode($json){
    $results = json_encode(array_filter($json, function($arr) use ($array){
        return preg_replace('~\[nrtfd]~', '\\', $arr);
    }));

    return $results;
}

print_r($results);

FYI, the above returns: {"name":"some text \n\r text"}instead of {"name":"some text nr text"}

仅供参考,以上返回:{"name":"some text \n\r text"}而不是{"name":"some text nr text"}

回答by olga

You could use PHP_EOLfor a new line. Where to include new line depends on how you want. In the case below, i need a new line after the last closing square bracket and each curly bracket:

您可以PHP_EOL用于新行。在何处包含新行取决于您想要的方式。在下面的情况下,我需要在最后一个右方括号和每个大括号之后换行:

tit1: {
"prop1" : [ "", "", []], 
"prop2" : [ "", "", []]
}, 
tit2: {
"prop1" : [ "", "", []], 
"prop2" : [ "", "", []]
}

The function is

功能是

$jsonDataTxt = $this->own_format_json($jsonData);
file_put_contents("C:/Users/mm/Documents/Data.json", $jsonDataTxt);


function own_format_json($json, $html = false) {
        $tabcount = 0; 
        $result = ''; 
        $bnew = 0;
        $brack=0;  
        $tab = "\t"; 
        $newline = PHP_EOL; 
        for($i = 0; $i < strlen($json); $i++) { 
            $char = $json[$i]; 
            if($char!==',' && $bnew===1) { $bnew=0; $result.=  $newline; } //insert new line after ], which is not proceeded by ,
            switch($char) { 
                case '{': 
                    $tabcount++; 
                    $result .= $char . $newline . str_repeat($tab, $tabcount); 
                    break; 
                case '}': 
                    $tabcount--; 
                    $result = trim($result) . $newline . str_repeat($tab, $tabcount) . $char . $newline; 
                    break; 
                case '[': 
                    $brack++; 
                    $result .= $char;// . $newline . str_repeat($tab, $tabcount); 
                    break; 
                case ']': 
                    $brack--;
                    $result .= $char;// . $newline . str_repeat($tab, $tabcount); 
                    if($brack===0) { $bnew=1; }
                    //echo "<br><br> case  ]  char=".$char.',   brack='.$brack. ",  bnew=".$bnew.",   result=".$result ; 
                    break; 
                case ',': 
                    $result .= $char;// . $newline . str_repeat($tab, $tabcount); 
                    if($bnew===1) { $bnew=0; $result.=  $newline; } //insert new line after ],
                    break; 
                case '"': 
                    $result .= $char; 
                    break; 
                default: 
                    $result .= $char; 
            } 
        } 
    return $result; 
   }