Parsing JSON Objects in PHP with json_decode
When attempting to parse JSON data in PHP, it's essential to understand the object structure of the returned data. The json_decode function, as seen in the example below, can be used to transform JSON data into a PHP array or object.
<br>$url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710';<br>$json = file_get_contents($url);<br>$data = json_decode($json, true);<br>
However, in the case provided, the original code encountered issues due to incorrect path navigation within the JSON object. To parse the desired data, the following modifications can be made:
<br>foreach ($data['data']['weather'] as $item) {</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">print $item['date']; print ' - '; print $item['weatherDesc'][0]['value']; print ' - '; print '<img src="' . $item['weatherIconUrl'][0]['value'] . '" border="0" alt="" />'; print '<br>';
}
It's important to note that setting the second parameter of json_decode to true returns an array, making the -> syntax invalid. This necessitates the use of array indexing instead.
For a more user-friendly experience, consider installing the JSONview Firefox extension. It enables the display of JSON documents in a formatted tree view, similar to the way Firefox handles XML structures. This can greatly simplify the task of navigating and understanding JSON data.
以上是如何使用 json_decode 解析 PHP 中的 JSON 物件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!