php json_encode没有逃避新行

时间:2012-06-29 15:28:58

标签: php json

我正面临着json_encode的一些问题。

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

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

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

我正在使用php 5.3.8

修改

这是我正在使用的原始代码

$attr = array();
for($i=0; $i < count($_POST['key']); $i++){
    $attr[$_POST['key'][$i]] = $_POST['value'][$i];
}
echo json_encode(array('custom' => $attr));

这些POST值来自表单。

5 个答案:

答案 0 :(得分:10)

<强> Newlines are not valid characters inside of JSON strings 即可。这是预期的行为:

  

     

任何Unicode字符,除了&#34;或\或控制字符

     
      
  • \&#34;
  •   
  • \
  •   
  • /
  •   
  • \ B'/ LI>   
  • \˚F
  •   
  • \ n
  •   
  • \ r
  •   
  • \吨
  •   
  • \ u four-hex-digits
  •   

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

现在我们有'\n'(字面意思是反斜杠后跟&#39; n&#39;),如果没有正确转义,它将作为n保存在数据库中。 是您遇到的问题。

解决方案

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

答案 1 :(得分:2)

我不相信json_encode是你的问题。我的猜测是你的数据库正在解释\作为转义字符,因此它只是将它们剥离出来。

要解决此问题,只需使用addslashes转义转义字符:

$results=addslashes($results);

答案 2 :(得分:2)

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

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

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

感谢每一个人。

答案 3 :(得分:0)

您可以手动转义它们:

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

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

print_r($results);

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

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

    return $results;
}

print_r($results);

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

答案 4 :(得分:0)

您可以将PHP_EOL用于新行。包含新行的位置取决于您的需求。在下面的例子中,我需要在最后一个右方括号和每个花括号之后的新行:

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

功能是

$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; 
   }
相关问题