Decoding JSON Array of Objects in PHP, is it the b

2020-07-22 18:13发布

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.

My javascript is as follows:

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

        alert(data);

    }
});

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":""}]

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\":\"\"}]

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?

Any help much appreciated!

Thanks, -Ben

标签: php jquery json
2条回答
虎瘦雄心在
2楼-- · 2020-07-22 18:43

This has to do with Magic Quotes
Is better to disable this annoying old feature and forget those problems.
You can disabled following these instructions.

查看更多
Viruses.
3楼-- · 2020-07-22 18:44

Use stripslashes ( $string ) - http://php.net/manual/en/function.stripslashes.php

This should work

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

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

However, as already pointed by the others, it's better to disable magic_quotes_gpc.

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

magic_quotes_gpc = On

Set it to Off and restart the server.

查看更多
登录 后发表回答