How to process JSON in PHP?

Here is the JSON which is sent asynchronously to my php page. It is essentially a product list, which will be inserted into my mySQL database.

My issue is decoding the JSON in PHP. I can do this fine in js with the 'eval' function, but in PHP my efforts have resulted in a complicated series of explode and implode functions.

{
    "Product": [
        {
            "Product_Title": "Cloth",
            "Product_Description": "Here is cloth",
            "Price": "100",
            "Category_ID": "1"
        },
        {
            "Product_Title": "Cloth",
            "Product_Description": "Here is cloth",
            "Price": "100",
            "Category_ID": "1"
        },
        {
            "Product_Title": "Cloth",
            "Product_Description": "Here is cloth",
            "Price": "100",
            "Category_ID": "1"
        }
    ]
}

I know php has a built in json_decode function, but in the PHP documentation they only show how to handle an array.

Any advice or help is really appreciated

Taylor


Solution 1:

If you call json_decode($data,true);, your data will be:

Array(
    "Product"=>Array(
        Array(
            "Product_Title"=>"Cloth",
            "Product_Description"=>"Here is cloth",
            "Price"=>"100",
            "Category_ID"=>"1"
        ),
        Array(
.............
        )
    )
);

What is wrong with that?

Solution 2:

If you want to preserve the stdClass objects, you need to use the object-property syntax.

<?php

$json = '{
    "Product": [
        {
            "Product_Title": "Cloth",
            "Product_Description": "Here is cloth",
            "Price": "100",
            "Category_ID": "1"
        },
        {
            "Product_Title": "Cloth",
            "Product_Description": "Here is cloth",
            "Price": "100",
            "Category_ID": "1"
        },
        {
            "Product_Title": "Cloth",
            "Product_Description": "Here is cloth",
            "Price": "100",
            "Category_ID": "1"
        }
    ]
}
';

$json_decoded = json_decode($json);

// Note, it's usually a bad idea to use use count() like this;
// cache the count before the for() in a variable and use that.
// This is for demo purposes only. :)
for ($i = 0; $i < count($json_decoded->{'Product'}); $i++) {
    echo "Products:
" . $json_decoded->{'Product'}[$i]->{'Product_Title'} . "
" . $json_decoded->{'Product'}[$i]->{'Product_Description'} . "
" . $json_decoded->{'Product'}[$i]->{'Price'} . "
" . $json_decoded->{'Product'}[$i]->{'Category_ID'} . "

";
}

?>

Outputs:

Products:
Cloth
Here is cloth
100
1

Products:
Cloth
Here is cloth
100
1

Products:
Cloth
Here is cloth
100
1

http://codepad.org/JxYAO5De