Home > Blockchain >  Converting an Axios GET Request to PHP cURL
Converting an Axios GET Request to PHP cURL

Time:03-03

I have an Axios HTTP GET request I'd to convert to PHP cURL.

Axios Request

axios({
    method: 'get',
    url: 'https://api.sample.com/123456789/',
    data: {
        apikey: '987654321',
        id: '123123',
    }
}).then(function ( response ) {
    console.log( response );
});

How do I make this request in PHP cURL, sending the apikey and id data, then echoing the response?

cURL I Was Trying

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

Result

NULL

CodePudding user response:

when you set data together with method: 'GET', axios will set Content-Type: application/json and.. completely ignore the post data. so the correct translation is:

<?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 this feels like an axios bug, it wouldn't surprise me if this changes in a future version of axios.
  • Related