Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP json_decode not working - displays NULL output

Tags:

json

php

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?

like image 247
user2268281 Avatar asked Dec 09 '22 15:12

user2268281


1 Answers

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.

like image 62
xbonez Avatar answered Dec 11 '22 09:12

xbonez