2013-08-02 49 views
2

我想從一個格式良好的json文件中檢索具有多維數組中的值的值。天氣預報在我的情況。如何從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中的知識不足以完成這項工作。
謝謝

+4

代碼工作正常,我。檢查您是否在php中設置了allow_url_fopen設置。嘗試添加'回聲$ json_string;',看看JSON是從服務器 –

+0

正確服用爲什麼你使用'$ parsed_json - > {「預測」}'?這應該工作:'$ parsed_json-> forecast'如果該字段可用。 – NDM

+0

@JerzyZawadzki是的,代碼突然開始工作。感謝Nicky De Maeyer,謝謝你的提示。 – Abhik

回答

1

代碼對我的工作很好。

但我不確定你爲什麼要爲$parsed_json->{'forecast'}而不是$parsed_json->forecast訪問屬性值。你的方法有效,但它的醜陋和不一致。

+0

謝謝Ayman的小費。 – Abhik

1

你給出的這段代碼工作得很好。 您應該檢查是否允許file_get_contents()訪問URL。

您可以通過,如果allow_url_fopen你的php.ini設置爲1,檢查這樣做。

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 
} 
?> 

enter image description here