Rumah > Artikel > pembangunan bahagian belakang > Bagaimanakah saya menghuraikan objek JSON dalam PHP dengan json_decode?
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> <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.
Atas ialah kandungan terperinci Bagaimanakah saya menghuraikan objek JSON dalam PHP dengan json_decode?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!