嘿,我在使用cURL (我不能使用file_get_contents,因为我的网络主机不允许它)来访问wunderground weather 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} ";任何帮助都将不胜感激!
发布于 2013-05-20 10:46:26
json_decode的第二个参数允许您将JSON解码为array而不是object。试着打开它,这样你就永远知道你在处理什么:
$response = json_decode($result, true);
如果失败,可能是因为您没有正确使用API?
https://stackoverflow.com/questions/16640814
复制相似问题