我正在尝试从accuweither API获取json数据,用于PHP中的locationKey。输出为:file_get_contents(https://dataservice.accuweather.com/forecasts/v1/daily/1day/55488?apikey=0NSY9T1tFGo0NIXOYp23lro8DsuOcwPJ): failed to open stream: HTTP request failed!
<?php
$url = "https://dataservice.accuweather.com/forecasts/v1/daily/1day/55488?apikey=0NSY9T1tFGo0NIXOYp23lro8DsuOcwPJ";
$json = file_get_contents($url);
$data = json_decode($json,true);
print_r($data);
?>
CCD_ 2被启用。
我该怎么办?
编辑:我按如下方式更改了代码,但它不起作用
function weather(){
$url='http://dataservice.accuweather.com/forecasts/v1/daily/5day/55488?apikey=0NSY9T1tFGo0NIXOYp23lro8DsuOcwPJ';
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl,CURLOPT_FAILONERROR,true);
curl_setopt($curl, CURLOPT_URL, $url);
$result = curl_exec($curl);
$res=(object)array(
'response' => curl_exec( $curl ),
'status' => curl_getinfo( $curl, CURLINFO_RESPONSE_CODE ),
'info' => (object)curl_getinfo( $curl ),
'errors' => curl_error( $curl )
);
curl_close($curl);
echo 'response:'.$res->response;
echo '<br>';
echo 'status:'.$res->status;
echo '<br>';
echo 'errors:'.$res->errors;
}
结果是具有以下特征的空白页:
response:
status:0
errors:Empty reply from server
Fetch
api似乎是最简单的解决方案,因为端点确实存在Access-Control-Allow-Origin: *
头-下面是一个简单的示例来说明基础知识。
const url='https://dataservice.accuweather.com/forecasts/v1/daily/1day/55488?apikey=0NSY9T1tFGo0NIXOYp23lro8DsuOcwPJ';
fetch( url )
.then( r=>r.json() )
.then( json=>{
const out=document.querySelector('output');
Object.keys( json ).forEach( k=>{
let div=document.createElement('div');
out.append( div );
let h1=document.createElement('h1');
h1.textContent=k;
div.append(h1);
// etc
});
json.DailyForecasts.forEach( obj=>{
console.info( obj )
})
})
<output></output>
在PHP中,您可以使用curl
轻松地从AccuWeather API获取响应。下面的curl函数有一个cacert
变量,它指向一个有效的cacert.pem
文件——这在协商SSL连接时通常是需要的,如下所示。
<?php
function curl( $url=false ){
$cacert='c:/wwwroot/cacert.pem';
$curl=curl_init();
if( parse_url( $url, PHP_URL_SCHEME )=='https' ){
curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, true );
curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt( $curl, CURLOPT_CAINFO, $cacert );
}
curl_setopt( $curl, CURLOPT_URL, trim( $url ) );
curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $curl, CURLOPT_FAILONERROR, true );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl, CURLOPT_TIMEOUT, 60 );
curl_setopt( $curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)' );
curl_setopt( $curl, CURLOPT_ENCODING, '' );
$res=(object)array(
'response' => curl_exec( $curl ),
'status' => curl_getinfo( $curl, CURLINFO_RESPONSE_CODE ),
'info' => (object)curl_getinfo( $curl ),
'errors' => curl_error( $curl )
);
curl_close( $curl );
return $res;
}
$url='https://dataservice.accuweather.com/forecasts/v1/daily/1day/55488?apikey=0NSY9T1tFGo0NIXOYp23lro8DsuOcwPJ';
$res=curl( $url );
if( $res->status==200 ){
printf('<pre>%s</pre>',print_r( json_decode( $res->response ),true ) );
}
?>
这就产生了:
stdClass Object
(
[Headline] => stdClass Object
(
[EffectiveDate] => 2022-01-14T07:00:00-05:00
[EffectiveEpochDate] => 1642161600
[Severity] => 4
[Text] => Turning much colder today and tomorrow
[Category] => cooler
[EndDate] => 2022-01-15T19:00:00-05:00
[EndEpochDate] => 1642291200
[MobileLink] => http://www.accuweather.com/en/ca/toronto/m5h/daily-weather-forecast/55488?lang=en-us
[Link] => http://www.accuweather.com/en/ca/toronto/m5h/daily-weather-forecast/55488?lang=en-us
)
[DailyForecasts] => Array
(
[0] => stdClass Object
(
[Date] => 2022-01-13T07:00:00-05:00
[EpochDate] => 1642075200
[Temperature] => stdClass Object
(
[Minimum] => stdClass Object
(
[Value] => 12
[Unit] => F
[UnitType] => 18
)
[Maximum] => stdClass Object
(
[Value] => 34
[Unit] => F
[UnitType] => 18
)
)
[Day] => stdClass Object
(
[Icon] => 19
[IconPhrase] => Flurries
[HasPrecipitation] =>
)
[Night] => stdClass Object
(
[Icon] => 43
[IconPhrase] => Mostly cloudy w/ flurries
[HasPrecipitation] =>
)
[Sources] => Array
(
[0] => AccuWeather
)
[MobileLink] => http://www.accuweather.com/en/ca/toronto/m5h/daily-weather-forecast/55488?lang=en-us
[Link] => http://www.accuweather.com/en/ca/toronto/m5h/daily-weather-forecast/55488?lang=en-us
)
)
)
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Allow: GET, POST, OPTIONS, PUT, DELETE");
$method = $_SERVER['REQUEST_METHOD'];
if($method == "OPTIONS") {
die();
}
$api_key="yourapikey";
//$id_ciudad=$_GET["id_ciudad"];//obtenemos el id de la ciudad
$url = "http://dataservice.accuweather.com/currentconditions/v1/36300?apikey=$api_key&language=es-bo&details=true";
$json = file_get_contents($url);
$obj_json = json_decode(html_entity_decode($json),true);
//Vemos si hay algun error
$json_errors = array(
JSON_ERROR_NONE => 'No error has occurred',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
);
echo 'Last error : ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL;
//imprimimos el json entero
//print_r($obj_json);
//imprimimos un dato del json en este caso el tiempo en formato Epoch
echo $obj_json[0]['EpochTime'];
?>