使用JSON_decode解析PHP中的JSON对象
我试图从一个以使用JSON_decode解析PHP中的JSON对象,php,json,Php,Json,我试图从一个以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, TR
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",
... },
... ]
}
}
}
试试这个例子
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
注-两个负数等于一个正数。:) 似乎您忘记了[“值”]或
->value
:
echo $data[0]->weather->weatherIconUrl[0]->value;
如果改为使用以下选项:
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
如果为TRUE,则返回数组而不是对象。这似乎有效:
$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>';
}
$url='1!'http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,奥地利&format=json&num_of_days=5&key=8f2d1ea151085304102710%22';
$content=file\u get\u contents($url);
$json=json_decode($content,true);
foreach($json['data']['weather']作为$item){
打印$item['date'];
打印'-';
打印$item['weatherDesc'][0]['value'];
打印'-';
打印“”;
打印“
”;
}
如果将json_decode的第二个参数设置为true,则会得到一个数组,因此不能使用->语法。我还建议您安装,这样您就可以在一个格式良好的树视图中查看生成的json文档,类似于Firefox显示XML结构的方式。这让事情变得容易多了 您必须首先确保您的服务器允许远程连接,以便功能
文件获取内容($url)
工作正常,大多数服务器出于安全原因禁用此功能。在编辑代码时(因为轻度强迫症),我注意到天气也是一个列表。你应该考虑一些类似
echo $data[0]->weather[0]->weatherIconUrl[0]->value;
要确保您使用的weatherIconUrl用于正确的日期实例。当您解码json时,强制它返回数组而不是对象
$data = json_decode($json, TRUE); -> // TRUE
这将返回一个数组,您可以通过提供键来访问这些值 我有一个类似的深嵌套json,当我将它转换为数组时,它会让我非常痛苦。我想不出正确的方法来深入数组以获得所需的项目。看起来很简单,但作为一个对php相当陌生的人,您的简单解决方案正是我所需要的。谢谢