【问题标题】:Decoding JSON Array of Objects in PHP, is it the back slashes?在 PHP 中解码 JSON 对象数组,是反斜杠吗?
【发布时间】:2011-12-13 23:13:49
【问题描述】:

所以我使用 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

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

非常感谢任何帮助!

谢谢, -本

【问题讨论】:

  • 打印 $data 值,看看 json_decode 之后这个变量的值是多少 ...

标签: php jquery json


【解决方案1】:

使用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 "<pre>";
print_r($data);

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

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

magic_quotes_gpc = On

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

【讨论】:

  • Simone,你是我的救星,我爱你。谢谢! :D
  • 虽然显然是一个有效的答案,但这是与症状而不是原因作斗争:magic_quotes_gpc。把它们关掉,你就再也不用担心这样的事情了。
【解决方案2】:

这与Magic Quotes有关
最好禁用这个烦人的旧功能并忘记这些问题。
您可以禁用关注these instructions

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-26
    • 1970-01-01
    • 2011-08-10
    • 2017-05-12
    • 1970-01-01
    • 2016-06-16
    • 2013-11-14
    相关资源
    最近更新 更多