I am trying to retrieve values from a well formed json file which has the values in multidimensional arrays. Weather forecasts in my case.
Here is the sample of the files I am working on. PasteBin (My apologies, the file is to long to paste here).
Here is the code I used, but it's returning absolutely nothing.
<?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
}
?>
Please help me out. My knowledge in php isn't sufficiant to make this work.
Thanks
Code works fine on my end.
But I am not sure why you're doing $parsed_json->{'forecast'}
instead of $parsed_json->forecast
for accessing the property values. Your method works, but its just ugly and inconsistent.
The piece of code you've given works absolutely fine. You should check if file_get_contents()
is allowed to access the URL.
You can do so by checking if allow_url_fopen
is set to 1 in your php.ini.
This is working as expected at my end :
<?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
}
?>