用PHP解码对象的JSON数组,是反斜线吗?

用PHP解码对象的JSON数组,是反斜线吗?

问题描述:

因此,我将使用JavaScript的JSON字符串对象数组发布到PHP脚本,而在php中解码时遇到了实际问题.

So I'm posting an array of objects in a JSON string using javascript to a PHP script and I'm having real problems decoding it in the php.

我的JavaScript如下:

My javascript is as follows:

$.ajax({
    type: 'POST',
    url: "question_save.php",
    data: {myJson:  JSON.stringify(jsonArray)},
    success: function(data){

        alert(data);

    }
});

发送到PHP的字符串如下:

The string sent to the PHP looks like this:

[{"content":"Question text"},{"answerContent":"Some answer text","score":"234","responseChecked":0,"responseContent":""},{"answerContent":"","score":"0","responseChecked":0,"responseContent":""}]

如果我回显$ _POST ['myJson'],我会得到:

If I echo $_POST['myJson'] I get this:

[{\"content\":\"Question text\"},{\"answerContent\":\"Some answer text\",\"score\":\"234\",\"responseChecked\":0,\"responseContent\":\"\"},{\"answerContent\":\"\",\"score\":\"0\",\"responseChecked\":0,\"responseContent\":\"\"}]

但是当我想要解码JSON并像这样循环遍历...

Yet when I want to decode the JSON and loop through it like this...

$json = $_POST['myJson'];
$data = json_decode($json, true);

foreach ($data as &$value) {
    echo("Hi there");
}

...我收到此错误:

...I get this error:

Warning:  Invalid argument supplied for foreach() in /home/thecrime/public_html/test1/question_save.php on line 15

我真的不明白我在犯什么愚蠢的错误,这与反斜杠有关吗?

I really don't understand what silly mistake I'm making, is it something to do with the back slashes?

任何帮助,不胜感激!

谢谢, -奔

使用stripslashes ( $string )- http://php.net/manual/zh/function.stripslashes.php

这应该有效

$json = $_POST['myJson'];
$json_string = stripslashes($json)
$data = json_decode($json_string, true);

// simple debug
echo "<pre>";
print_r($data);


但是,正如其他人已经指出的那样,最好禁用magic_quotes_gpc.

打开您的php.ini文件并搜索以下行:

Open your php.ini file and search for this row:

magic_quotes_gpc = On

将其设置为Off并重新启动服务器.

Set it to Off and restart the server.