我有一個要轉換為 PHP cURL 的 Axios HTTP GET 請求。
Axios 請求
axios({
method: 'get',
url: 'https://api.sample.com/123456789/',
data: {
apikey: '987654321',
id: '123123',
}
}).then(function ( response ) {
console.log( response );
});
如何在 PHP cURL 中發出這個請求,發送 apikey 和 id 資料,然后回顯回應?
我正在嘗試的 cURL
<?php
$url = 'https://api.sample.com/123456789/';
$body_arr = [
'apikey' => '987654321',
'id' => '123123',
];
$data = http_build_query($body_arr);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$result_arr = json_decode($result, true);
echo '<pre>';
var_dump( $result_arr );
echo '</pre>';
?>
結果
NULL
uj5u.com熱心網友回復:
當您將資料與 一起設定時method: 'GET',axios 將設定Content-Type: application/json并.. 完全忽略發布資料。所以正確的翻譯是:
<?php
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'https://api.sample.com/123456789/',
CURLOPT_HTTPGET => 1,
CURLOPT_HTTPHEADER => array(
// this is not correct, there is no content-type,
// but to mimic Axios's behavior with setting `data` on GET requests, we send this
// incorrect header:
'Content-Type: application/json'
)
));
curl_exec($ch);
- fwiw這感覺就像一個 axios 錯誤,如果這在未來版本的 axios 中發生變化,我不會感到驚訝。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/436720.html
