Home >Backend Development >PHP Tutorial >How Do I Access Data from JSON Using PHP?

How Do I Access Data from JSON Using PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-12-23 10:09:40403browse

How Do I Access Data from JSON Using PHP?

How do I access data from JSON with PHP?

PHP provides the json_decode() function to decode a JSON string and convert it into a PHP data structure. Let’s dig into how to access the results:

Object property access:

Object properties can be accessed via $object->property For example:

$json = '{"type": "donut", "name": "Cake"}';
$yummy = json_decode($json);
echo $yummy->type; // "donut"

Array element access:

Array elements can be accessed through $array[0] For example:

$json = '["Glazed", "Chocolate with Sprinkles", "Maple"]';
$toppings = json_decode($json);
echo $toppings[1]; // "Chocolate with Sprinkles"

Nested item access:

Nested items can be accessed through consecutive attributes and indexes, such as $object-> array[0]->etc. :

$json = '{"type": "donut", "name": "Cake", "toppings": [{"id": "5002", "type": "Glazed"}]}';
$yummy = json_decode($json);
echo $yummy->toppings[0]->id; // "5002"

Convert to associative array:

Pass true as the second parameter of json_decode() to convert JSON The object is decoded into an associative array whose keys are strings:

$json = '{"type": "donut", "name": "Cake"}';
$yummy = json_decode($json, true);
echo $yummy['type']; // "donut"

Accessing the associative array items:

can be done via foreach (array_expression as $key => $ value) Traverse keys and values:

$json = '{"foo": "foo value", "bar": "bar value", "baz": "baz value"}';
$assoc = json_decode($json, true);
foreach ($assoc as $key => $value) {
    echo "The value of key '$key' is '$value'" . PHP_EOL;
}

Output:

The value of key 'foo' is 'foo value'
The value of key 'bar' is 'bar value'
The value of key 'baz' is 'baz value'

Unknown data structure:

If you don’t know the data structure, please refer to the related documentation or use print_r() Check the result:

print_r(json_decode($json));

json_decode() returns null:

This happens when the JSON is null or invalid. Use json_last_error_msg() to check error messages.

Special character attribute names:

Use {"@attributes":{"answer":42}} to access attribute names with special characters:

$json = '{"@attributes":{"answer":42}}';
$thing = json_decode($json);
echo $thing->{'@attributes'}->answer; //42

The above is the detailed content of How Do I Access Data from JSON Using PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn