如何使用 json_decode 解析 PHP 中的 JSON 物件?

Patricia Arquette
發布: 2024-11-14 19:42:02
原創
986 人瀏覽過

How do I parse JSON objects in PHP with 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>
<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中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門推薦
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板