2013-05-04 64 views
0

返回我有如下一個簡單的腳本:打印可變從API

<?php 
    header('Content-Type: text/plain; charset=utf-8;'); 
    $file = file_get_contents("http://weather.justcode.us/api.php?city=Suzhou"); 
    print_r(json_decode($file)); 
?> 

,並返回

stdClass Object 
(
    [apiVersion] => 1.0 
    [data] => stdClass Object 
     (
      [location] => Suzhou, CHN 
      [temperature] => 68 
      [skytext] => Clear 
      [humidity] => 60 
      [wind] => 13 
      [date] => 2013-05-04 
      [day] => Saturday 
     ) 

) 

如何打印(例如)只是數據 - >位置,或者只是數據 - >日期?噢,如果這是一個簡單的問題,請提前道歉。

回答

1

試試這個,

<?php 
header('Content-Type: text/plain; charset=utf-8;'); 
$file = file_get_contents("http://weather.justcode.us/api.php?city=Suzhou"); 
$values= json_decode($file); 
$data=$values->data; 
echo $data->location; 

?> 

輸出

Suzhou, CHN 

在這裏,您可以像訪問任何數據,

$data->location,data->date etc 
1

json_decode只是返回一個簡單的對象。使用->來訪問其屬性。

echo $file->data->location; 
echo $file->data->date;