我正在尝试从此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;
答案 0 :(得分: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;
答案 1 :(得分: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.