2013-05-20 59 views
0

嘿我有一些問題使用cURL(我不能使用file_get_contents,因爲我的虛擬主機不會允許它)訪問wunderground天氣api的部分。使用cURL與wunderground api

當我使用下面的代碼來訪問天氣狀況的信息,我覺得沒有問題責任:

<? $json_url = 'http://api.wunderground.com/api/b2b4a1ad0a889006/geolookup/conditions 
    /q/IA/Cedar_Rapids.json'; 



// jSON String for request 
$json_string = '[http://api.wunderground.com/api/b2b4a1ad0a889006/geolookup/conditions 
/q/IA/Cedar_Rapids.json]'; 

// Initializing curl 
$ch = curl_init($json_url); 

// Configuring curl options 
$options = array(
CURLOPT_RETURNTRANSFER => true, 
); 

// Setting curl options 
curl_setopt_array($ch, $options); 

// Getting results 
$result = curl_exec($ch); // Getting jSON result string 

$parsed_json = json_decode($result); 
$location = $parsed_json->{'location'}->{'city'}; 
$temp_f = $parsed_json->{'current_observation'}->{'temp_f'}; 
echo "Current temperature in ${location} is: ${temp_f}\n"; 
?> 

然而,當我做細微的修改,以獲得使用下面的代碼漲潮和退潮數據我什麼也沒得到:

<? $json_url = 'http://api.wunderground.com/api/b2b4a1ad0a889006/tide/q/NJ/Wildwood.json'; 



// jSON String for request 
$json_string = '[http://api.wunderground.com/api/b2b4a1ad0a889006/tide/q/NJ/Wildwood.json]'; 

// Initializing curl 
$ch = curl_init($json_url); 

// Configuring curl options 
$options = array(
CURLOPT_RETURNTRANSFER => true, 
); 

// Setting curl options 
curl_setopt_array($ch, $options); 

// Getting results 
$result = curl_exec($ch); // Getting jSON result string 

$tide_time = $parsed_json->{'tide'}->{'tideSummary'}->{'date'}->{'pretty'}; 
echo "High tide is at ${tide_time} "; 
?> 

現在我知道這個問題可能是我處理在第二個例子中的數組,但我不知道如何修改代碼。我知道第一個低潮的記錄是[3],我試着做了下面的修改,但沒有運氣。

$tide_time = $parsed_json->{'tide'}->{'tideSummary'}->[3]->{'date'}->{'pretty'}; 
echo "High tide is at ${tide_time} "; 

任何幫助將不勝感激!

回答

0

json_decode的第二個參數允許您將JSON解碼爲array而不是object。嘗試打開上,所以你總是知道你正在處理什麼用:

$response = json_decode($result, true);

如果失敗了,也許你沒有正確使用API​​?