Parsing JSON Objects in PHP with json_decode
To parse JSON objects in PHP, you can use the json_decode() function. This function takes a JSON string as an input and returns the corresponding PHP data structure.
Using json_decode() for an Example JSON String
Consider a JSON string obtained from a weather API:
{ "data": { "current_condition": [], "request": [], "weather": [ { "date": "2022-07-28", "weatherCode": "113", "weatherDesc": [ { "value": "Sunny" } ], "weatherIconUrl": [ { "value": "http:\/\/www.example.com/weather_icons/sunny.png" } ] }, // More weather data for subsequent days... ] } }
Code to Parse the JSON String
To parse this JSON string, you can use the following PHP code:
$json = '{"data": ... }'; // Assuming the JSON string is stored in $json $data = json_decode($json, true); // Accessing the weather data $weatherData = $data['data']['weather']; foreach ($weatherData as $weather) { echo $weather['date'] . ': ' . $weather['weatherDesc'][0]['value'] . '<br>'; echo '<img src="' . $weather['weatherIconUrl'][0]['value'] . '" />'; }
Tips
The above is the detailed content of How to Parse JSON Objects in PHP with json_decode()?. For more information, please follow other related articles on the PHP Chinese website!