[英]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.