在PHP中解码JSON对象数组,它是反斜杠吗?

所以我使用javascript将一个JSON字符串中的对象数组发布到PHP脚本中,并且我在php中解码它时遇到了实际问题。

我的javascript如下:

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

发送给PHP的字符串如下所示:

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

如果我回复$ _POST [‘myJson’]我得到这个:

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

然而,当我想解码JSON并像这样循环它…

 $json = $_POST['myJson']; $data = json_decode($json, true); foreach ($data as &$value) { echo("Hi there"); } 

…我收到此错误:

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

我真的不明白我正在制造什么愚蠢的错误,是否与反斜杠有关?

任何帮助非常感谢!

谢谢,-Ben

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

这应该工作

 $json = $_POST['myJson']; $json_string = stripslashes($json) $data = json_decode($json_string, true); // simple debug echo "
"; print_r($data);


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

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

 magic_quotes_gpc = On 

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

这与Magic Quotes有关
最好禁用这个恼人的旧function,并忘记这些问题。
您可以按照这些说明禁用。