首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将cURL与wunderground api结合使用

将cURL与wunderground api结合使用
EN

Stack Overflow用户
提问于 2013-05-20 08:06:16
回答 1查看 1K关注 0票数 0

嘿,我在使用cURL (我不能使用file_get_contents,因为我的网络主机不允许它)来访问wunderground weather api的部分内容时遇到了一些问题。

当我使用以下代码访问有关天气条件的信息时,我没有任何问题:

代码语言:javascript
复制
<? $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";
?>

但是,当我使用以下代码进行轻微修改以获取涨潮和退潮数据时,我什么也得不到:

代码语言:javascript
复制
<? $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次,我试着做了下面的修改,但没有成功。

代码语言:javascript
复制
$tide_time = $parsed_json->{'tide'}->{'tideSummary'}->[3]->{'date'}->{'pretty'}; 
echo "High tide is at ${tide_time} ";

任何帮助都将不胜感激!

EN

回答 1

Stack Overflow用户

发布于 2013-05-20 10:46:26

json_decode的第二个参数允许您将JSON解码为array而不是object。试着打开它,这样你就永远知道你在处理什么:

$response = json_decode($result, true);

如果失败,可能是因为您没有正确使用API?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16640814

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档