Home > Article > Backend Development > How to Properly Parse Nested JSON Data in PHP?
Parsing JSON Objects in PHP with json_decode
When attempting to retrieve weather data from a JSON-formatted web service, you may encounter challenges. A common PHP request code that doesn't succeed:
$url = "http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710"; $json = file_get_contents($url); $data = json_decode($json, TRUE); echo $data[0]->weather->weatherIconUrl[0]->value;
To understand the issue, let's examine the JSON data you received:
{ "data": { "current_condition": [...], "request": [...], "weather": [ { "date": "2010-10-27", "precipMM": "0.0", "tempMaxC": "3", "tempMaxF": "38", "tempMinC": "-13", "tempMinF": "9", "weatherCode": "113", "weatherDesc": [{ "value": "Sunny" }], "weatherIconUrl": [{ "value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png" }], "winddir16Point": "N", "winddirDegree": "356", "winddirection": "N", "windspeedKmph": "5", "windspeedMiles": "3" }, ... ] } }
Notice that the weather data is nested within the "data" object. Therefore, to correctly parse the JSON, you need to modify your code:
$url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710'; $content = file_get_contents($url); $json = json_decode($content, true); foreach ($json['data']['weather'] as $item) { print $item['date']; print ' - '; print $item['weatherDesc'][0]['value']; print ' - '; print '<img src="' . $item['weatherIconUrl'][0]['value'] . '" border="0" alt="" />'; print '<br>'; }
Setting the second parameter of json_decode to true gives you an array, allowing you to access data using array indexing. The JSONview Firefox extension can also help visualize JSON structures and simplify parsing.
The above is the detailed content of How to Properly Parse Nested JSON Data in PHP?. For more information, please follow other related articles on the PHP Chinese website!