1

JSON string that i received from the API

{"accessTokenResponse":{"token":"562371e99fda4296a380547cb5bf9fab","token_type":"Bearer","expires_in_seconds":"77476","client_id":"LTcyMDI1NDI0OQ==","responseStatus":{"code":"100000","message":"Service operation completed successfully","messageDetails":"Access token assigned."}}}

Information that i wanted to extract

562371e99fda4296a380547cb5bf9fab //-->The Token

My attempt

<?php
    $user = "LTcyMDI1NDI0OQ==";
    $password = "MjAzMDI5MTU";
    $returnFormat = "json";
    $url = "https://sandbox.dhlecommerce.asia/rest/v1/OAuth/AccessToken?clientId=".$user.
    "&password=".$password."&returnFormat=".$returnFormat."";
    $method = "GET";
    $headers = array(
        "content-type: application/json",
    );

    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_URL => $url,
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_HTTPHEADER => $headers,
    ));

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

    $result = json_decode($response);

    curl_close($curl);   

    if ($err) {
        echo "cURL Error #:" . $err;
    } else {
        echo $result->token;                
    }
?>

The output:

Warning: Undefined property: stdClass::$token in C:\xampp\htdocs\Tracking\getToken.php on line 31

Did the JSON string that i received is in bad format?

Why does it says undefined property? Appreciate any helps. thanks!

Post that i've refer to: How do I extract data from JSON with PHP?

Kelvin Yong
  • 70
  • 1
  • 8
  • 3
    Whenever you're in doubt about an object's structure, it's best to `var_dump` your object to get a good visual representation of it. This would've indicated to you that you forgot one level in the response. Alternatively, you could always take the JSON response and paste it into an online JSON formatter to get a neat visual structure, which should've revealed the same. – El_Vanja May 10 '21 at 09:31
  • thank you for the suggestion. Have a good day! – Kelvin Yong May 10 '21 at 09:34

1 Answers1

1

token is in the accessTokenResponse object, so :

echo $result->accessTokenResponse->token;
Thomas
  • 410
  • 9
  • 14