codeigniter 从accuweather api url获取数据

aemubtdh  于 2022-12-07  发布在  其他
关注(0)|答案(2)|浏览(129)

我正在尝试从accuweather 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);
?>

allow_url_fopen已使能。
我该怎么办?

**编辑:**我按如下所示更改了代码,但它不起作用

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
h4cxqtbf

h4cxqtbf1#

Fetch api似乎是最简单的解决方案,因为端点确实有Access-Control-Allow-Origin: *头-下面是一个简单的例子来说明基本原理。
第一个
在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
                )

        )

)
at0kjp5o

at0kjp5o2#

<?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'];

?>

相关问题