user2268281
user2268281

Reputation: 87

PHP json_decode not working - displays NULL output

I'm trying to use JSON decode to retrieve some information but it's not working, it's just showing the data as null when I use var_dump

Here's the JSON formatted data passed in the URL

orderSummary={"orderInfo":[{"itemNumber":"1","quantity":"3","price":"5.99","productName":"Item_B"}]}

When I simply echo the un-decoded string I get the following

echo $_GET['orderSummary'];
//displays the following
{\"orderInfo\":[{\"itemNumber\":\"1\",\"quantity\":\"3\",\"price\":\"5.99\",\"productName\":\"Item_B\"}]}

However, when I try to decode it the result is null

$order = $_GET['orderSummary'];
$data = json_decode($order,true);
echo "<PRE>";
var_dump($data); die();
//displays the following
<PRE>NULL

Is it not properly formatted?

Upvotes: 4

Views: 10884

Answers (1)

Ayush
Ayush

Reputation: 42450

Run the input string through stripslashes() first.

$input = '{\"orderInfo\":[{\"itemNumber\":\"1\",\"quantity\":\"3\",\"price\":\"5.99\",\"productName\":\"Item_B\"}]}';

print_r(json_decode(stripslashes($input)));

Output

stdClass Object
(
    [orderInfo] => Array
        (
            [0] => stdClass Object
                (
                    [itemNumber] => 1
                    [quantity] => 3
                    [price] => 5.99
                    [productName] => Item_B
                )

        )

)

Demo

Alternatively

Turn off magic_quotes_gpc. Considering that it has been deprecated (and removed in 5.4), this the better option.

Upvotes: 14

Related Questions