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

$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;    

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

{ "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": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png" } ],
            "winddir16Point": "N",
            "winddirDegree": "356",
            "winddirection": "N",
            "windspeedKmph": "5",
            "windspeedMiles": "3" }, 
          { "date": "2010-10-28",
            ... },

          ... ]
        }
    }
}

推荐答案

This appears to work:

$url = 'http://www.worldweatheronline.com/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>';
}

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相关问答推荐

Swift解码错误类型与`Bool`type不一致

Pandas 对REST API的自定义响应

用 Jolt 替换 JSON 中的值

在这种情况下我如何实现 UnmarshalJSON 并且只为一个接口字段定义特殊行为?

使用 jolt 将对象数组转换为数组

使用本地 JSON api react TS Axios

PowerShell:如何将哈希表输出为 json 并使用 foreach 循环将其存储在变量中?

流编写器未写入 webapi 中的 JSON 文件

提交后使用 Rails 7 结合 JSON 标签进行标记

使用 JQ 从文件中删除重复的 JSON 块

将 ES6 类对象序列化为 JSON

Laravel5 Json 获取文件内容

Jackson 没有使用 @JsonProperty 覆盖 Getter

在 JSON.NET 中序列化派生类时的字段顺序

PHP json_encode json_decode UTF-8

你如何在 Arrays of Arrays 上 OPENJSON

雅虎财经全币种报价 API 文档

Javascript:如何判断 AJAX 响应是否为 JSON

Backbone.js 模型与集合

杰克逊自动将 Joda DateTime 格式化为 ISO 8601 格式