Json_decode() is the built-in PHP function to decode JSON.
Decoding JSON
$data = json_decode($json);
DataTypes
Decoded JSON can contain:
Object Properties
Access object properties with -> operator:
echo $object->property;
Array Elements
Access array elements with [] operator:
echo $array[0];
Nested Items
Access nested items by chaining dot or array operators:
echo $object->array[0]->etc;
Associative Arrays
Passing true as the second argument of json_decode() creates associative arrays:
echo $array['key'];
Iterating Associative Arrays
Use foreach loop to iterate over both keys and values:
foreach ($assoc as $key => $value) { echo "Key: $key, Value: $value"; }
Unknown Data Structure
json_decode() Returns Null
Special Characters in Object Properties
Use curly braces with string literals to access properties with special characters:
echo $thing->{'@attributes'}->answer;
JSON within JSON
Decode the outer JSON and the inner JSON string to access the data:
echo json_decode(json_decode($yummy->toppings)[0]->type;
Large JSON Files
Handle large JSON files using:
The above is the detailed content of How to Efficiently Extract and Access Data from JSON Files Using PHP?. For more information, please follow other related articles on the PHP Chinese website!