How to extract and access data from JSON with PHP?

Spread the love

Sometimes, we want to extract and access data from JSON with PHP.

In this article, we’ll look at how to extract and access data from JSON with PHP.

How to extract and access data from JSON with PHP?

To extract and access data from JSON with PHP, we can use the json_decode function.

For instance, we write

$json = '
{
    "type": "donut",
    "name": "strawberry"
}';

$food = json_decode($json);

echo $food ->type;

to call json_decode with the $json string to return an object with the JSON fields as properties of the object.

Therefore, we can use $food ->type to get the type field value.

If the JSON string is an arraym, then an array is returned.

For instance, if we write

$json = '
[
    "Glazed",
    "Strawberry",
    "Maple"
]';

$toppings = json_decode($json);

then $toppings is an array.

Conclusion

To extract and access data from JSON with PHP, we can use the json_decode function.

Leave a Reply

Your email address will not be published.