Question:
How can I extract and access data from JSON with PHP?

Problem:

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?


Solution:


<?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.


Answered by: >Jatin Dahiya

Credit: >StackOverflow


Blog links:

>How to add a Parsing PHP file in order to get an array of parameters?

>How to correct WordPress site errors after upgrading to PHP 8.2?

>How does Perl match a string containing a dot in PHP?

>How to use PHP to display MySQL results in an HTML table?


Nisha Patel

Nisha Patel

Submit
0 Answers