0

I use the following commands to get a Curl response from an Api:

  $curl = curl_init();

  curl_setopt_array($curl, array(
  CURLOPT_URL => "https://{api-url_goed_here}/api/v2/token",
  CURLOPT_RETURNTRANSFER => 1,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => '{"grant_type": "password","client_id": "'.$client_id.'","username":"'.$username.'","password":"'.$user_password.'"}',
  CURLOPT_HTTPHEADER => array(
    "content-type: application/json"
  ),
));

$responseArray = curl_exec($curl);
$err = curl_error($curl);

I get a response. It looks like an array when I use print_r($responseArray). But when I use var_dump($responseArray), I see that it actually a string:

    string(384) "Array
(
    [access_token] => #token_is_here
    [token_type] => bearer
    [expires_in] => 3600
    [refresh_token] => #refresh_token_is_here
    [uid] => 7
    [info] => Array
        (
            [name] => #name_is_here
            [code] => #some_code
            [email] => #some_mail_address
        )
    [policy] => Array
        (
            [write_hours] => 1
        )
)
"

How do I prevent to get a string as response? I'm aiming to get an array, because I want to extract the access_token

1
  • 5
    Looks like the server is generating output via print_r() when it should be using echo json_encode(). Perhaps the API devs accidentally left some debugging code in there? Commented Mar 20, 2019 at 16:08

3 Answers 3

1

As a temporary solution, you can use print_r_reverse function from php.net print_r documentation comments. Just add that function somewhere into your code and access to token like this:

$response = curl_exec($curl);
$responseArray = print_r_reverse($response);
echo $responseArray['token'];
Sign up to request clarification or add additional context in comments.

1 Comment

This does the trick, thanks! (with ['access_token'] to be exact)
0

Ultimately, a Curl response is meaningless for PHP. It is just a bunch of strings returned but a server.

Just make sure that you can handle what's being returned. And if you have any control over it, than change the return value some that Curl returns what you want in the script that is running at https://{api-url_goed_here}/api/v2/token.

The response could have been the source code of example.com if you make it point there.

Comments

0

I've had contact with the developer of the API. As it turns out: I have to add "accept: application/json" to the header in order to get a formatted response. Otherwise, I just get a print_r dump of the result.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.