0

我正在尝试从此 API 获取数据:

https://rapidapi.com/apilayernet/api/rest-countries-v1? 
endpoint=53aa5a08e4b0a705fcc323a6

我设法使用 wp_remote_get() 发出请求,但除了错误之外,我一直没有显示任何结果:

 The site is experiencing technical difficulties.

我只是指出我已经使用 Composer 在包含请求的 XAMPP 正确文件夹中设置 Composer.json 文件:

{
    "require-dev": {
        "mashape/unirest-php": "3.*"
    }
}

在我的代码中,我包含了 API 密钥的参数,如下所示,但由于某种原因不起作用:

$request = wp_remote_get( 'https://restcountries-v1.p.rapidapi.com/all', 
array(
"X-RapidAPI-Host" => "restcountries-v1.p.rapidapi.com",
"X-RapidAPI-Key" => "7fc872eb0bmsh1baf0c288235a1ep114aecjsn18f888f020c0"
 ) );
 if( is_wp_error( $request ) ) {
return false; // Bail early
}
$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body );
echo $data;
4

2 回答 2

0

wp_remote_get接受一个选项数组作为第二个参数,但您直接传递了标头。
它们应该headers位于选项内的嵌套数组中。

方法文档:https ://codex.wordpress.org/Function_Reference/wp_remote_get

$request = wp_remote_get('https://restcountries-v1.p.rapidapi.com/all', [
    'headers' => [
        'X-RapidAPI-Host' => 'restcountries-v1.p.rapidapi.com',
        'X-RapidAPI-Key' => '<apikey>',
    ],
]);

if (is_wp_error($request)) {
    return false; // Bail early
}

$body = wp_remote_retrieve_body($request);
$data = json_decode($body);
echo $data;
于 2019-07-19T00:54:36.500 回答
0

这是我从 Wordpress 获取的所有内容中使用的方法

$url = 'https://restcountries-v1.p.rapidapi.com/all'; //define url
$response = wp_remote_get($url, array(
       'headers'=> array('X-RapidAPI-Host' => 'restcountries-v1.p.rapidapi.com', //set header
                         'X-RapidAPI-Key' => '<apikey>'//set api key
                          ),
        'method'      => 'GET',//set method
        ));

 $decode = json_decode($response);// decode response
 echo "<pre>"; print_r($decode); die('dead');// display response on page wiothout any other information.
于 2019-07-19T08:28:59.277 回答