使用 json

编程入门 行业动态 更新时间:2024-10-21 17:26:36
本文介绍了使用 json_decode 在 PHP 中解析 JSON 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我尝试从以 JSON 格式提供数据的 Web 服务请求天气.我没有成功的 PHP 请求代码是:

I tried to request the weather from a web service supplying data in JSON format. My PHP request code, which did not succeed was:

$url="www.worldweatheronline/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;

这是返回的一些数据.为简洁起见,部分细节已被截断,但保留了对象完整性:

This is some of the data that was returned. Some of the details have been truncated for brevity, but object integrity is retained:

{ "data": { "current_condition": [ { "cloudcover": "31", ... } ], "request": [ { "query": "Schruns, Austria", "type": "City" } ], "weather": [ { "date": "2010-10-27", "precipMM": "0.0", "tempMaxC": "3", "tempMaxF": "38", "tempMinC": "-13", "tempMinF": "9", "weatherCode": "113", "weatherDesc": [ {"value": "Sunny" } ], "weatherIconUrl": [ {"value": "www.worldweatheronline/images/wsymbols01_png_64/wsymbol_0001_sunny.png" } ], "winddir16Point": "N", "winddirDegree": "356", "winddirection": "N", "windspeedKmph": "5", "windspeedMiles": "3" }, { "date": "2010-10-28", ... }, ... ] } } }

推荐答案

这似乎有效:

$url = 'www.worldweatheronline/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710%22'; $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>'; }

如果将 json_decode 的第二个参数设置为 true,则会得到一个数组,因此不能使用 -> 语法.我还建议您安装 JSONview Firefox 扩展,因此您可以在类似于 Firefox 显示 XML 结构的格式良好的树视图中查看生成的 json 文档.这让事情变得容易多了.

If you set the second parameter of json_decode to true, you get an array, so you cant use the -> syntax. I would also suggest you install the JSONview Firefox extension, so you can view generated json documents in a nice formatted tree view similiar to how Firefox displays XML structures. This makes things a lot easier.

更多推荐

使用 json

本文发布于:2023-10-27 11:18:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1533214.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!