292

This is intended to be a general reference question and answer covering many of the never-ending "How do I access data in my JSON?" questions. It is here to handle the broad basics of decoding JSON in PHP and accessing the results.

I have the JSON:

{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}

How do I decode this in PHP and access the resulting data?

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
user3942918
  • 25,539
  • 11
  • 55
  • 67
  • 2
    Related: [Able to see a variable in print_r()'s output, but not sure how to access it in code](http://stackoverflow.com/q/6322084/367456), interactive JSON exploration in context of PHP is possible here: http://array.include-once.org/ – hakre Mar 27 '15 at 21:09
  • 1
    Please can I know that why this question not consider as a duplicate question even 9 or less users marked as a duplicate for https://stackoverflow.com/questions/4343596/parsing-json-file-with-php? M – I am the Most Stupid Person Aug 09 '17 at 05:46
  • @IamtheMostStupidPerson I'll try to explain, even though your username makes me doubt you'll get it ;). This question is asked, and its answers are written, in a "canonical" way. As such, it's a better recipient for duplicate target than the other questions. – Félix Adriyel Gagnon-Grenier Feb 25 '18 at 20:13

1 Answers1

2
<?php
$jsonData = '{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

// Decode the JSON
$data = json_decode($jsonData, true);

// Access the data
$type = $data['type'];
$name = $data['name'];
$toppings = $data['toppings'];

// Access individual topping details
$firstTopping = $toppings[0];
$firstToppingId = $firstTopping['id'];
$firstToppingType = $firstTopping['type'];

// Print the data
echo "Type: $type\n";
echo "Name: $name\n";
echo "First Topping ID: $firstToppingId\n";
echo "First Topping Type: $firstToppingType\n";
?>

In this example, json_decode() is used to decode the JSON data into a PHP associative array. You can then access the individual elements of the array as you would with any PHP array.