我正在尝试从格式良好的json文件中检索值,该文件具有多维数组中的值。我的天气预报。
以下是我正在处理的文件示例。 PasteBin(道歉,文件要在此处粘贴)。
这是我使用过的代码,但它绝对没有返回。
<?php
// Get Forecasts
$json_string = file_get_contents("http://weather.mailchips.com/weather.json");
$parsed_json = json_decode($json_string);
$forecasts = $parsed_json->{'forecast'}->{'txt_forecast'}->{'forecastday'};
foreach ($forecasts as $forecast) { ?>
<div class="eachforecast">
<div class="fcday"><?php echo $forecast->{'title'};?></div>
<div class="fcicon"><?php echo $forecast->{'icon_url'};?></div>
<div class="fctext"><?php echo $forecast->{'fcttext_metric'};?></div>
</div>
<?php
}
?>
请帮帮我。我在php中的知识并不足以使这项工作。
感谢
答案 0 :(得分:2)
这在我的结尾处按预期工作:
<?php
$content=file_get_contents('http://weather.mailchips.com/weather.json');
$content= json_decode($content);
foreach($content->forecast->txt_forecast->forecastday as $day){
?>
<div class="eachforecast" style=" width:120px;border:1px solid gray;display:inline-block;vertical-align:top;height:150px;overflow:auto">
<div class="fcday"><?php echo $day->title;?></div>
<div class="fcicon"><img src="<?php echo $day->icon_url;?>"></div>
<div class="fctext"><?php echo $day->fcttext_metric;?></div>
</div>
<?php
}
?>
答案 1 :(得分:1)
我的代码工作正常。
但我不确定您为什么要$parsed_json->{'forecast'}
而不是$parsed_json->forecast
来访问属性值。你的方法有效,但它只是丑陋和不一致。
答案 2 :(得分:1)
你提供的代码片段绝对正常。
您应该检查是否允许file_get_contents()
访问该网址。
您可以通过检查php.ini中的allow_url_fopen
是否设置为1来执行此操作。