cURL を使用して wunderground weather api の一部にアクセスする際に問題が発生しました (私の Web ホストでは許可されていないため、file_get_contents を使用できません)。
次のコードを使用して気象条件に関する情報にアクセスすると、何の問題もありません。
<? $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} ";
?>
これで、2 番目の例で配列を扱っていることが問題である可能性があることがわかりましたが、コードを変更する方法がわかりません。最初の干潮の記録が [3] であることはわかっています。
$tide_time = $parsed_json->{'tide'}->{'tideSummary'}->[3]->{'date'}->{'pretty'};
echo "High tide is at ${tide_time} ";
どんな助けでも大歓迎です!