[英]Using cURL with wunderground api
嘿,我在使用cURL時遇到了一些問題(我無法使用file_get_contents,因為我的網絡托管商不允許使用它)來訪問部分地下氣象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} ";
任何幫助將不勝感激!
json_decode
的第二個參數允許您將JSON解碼為array
而不是object
。 嘗試將其打開,以便您始終知道要處理的內容:
$response = json_decode($result, true);
如果失敗,則說明您未正確使用API?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.