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?
My Answer:
To decode the JSON in PHP and access the resulting data, you can use the `json_decode()` function to convert the JSON string into a PHP variable. Here's an example of how you can do this with the provided JSON:
php
$json = '{
"type": "donut",
"name": "Cake",
"toppings": [
{ "id": "5002", "type": "Glazed" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5004", "type": "Maple" }
]
}';
$data = json_decode($json);
// Accessing the data
echo $data->type; // Output: donut
echo $data->name; // Output: Cake
foreach ($data->toppings as $topping) {
echo $topping->id . ': ' . $topping->type . '
';
}
// Output:
// 5002: Glazed
// 5006: Chocolate with Sprinkles
// 5004: Maple
In this example, we first decode the JSON string using `json_decode()` and store the resulting data in the `$data` variable. We can then access the individual properties of the JSON object using object notation (`->`). In the case of an array within the JSON, such as the "toppings" array, we can iterate over it using a `foreach` loop to access each item within the array.
Rate this post
3 of 5 based on 9694 votesComments