Skip to content
Advertisement

Extracting json string with PHP

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:xampphtdocsTrackinggetToken.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?

Advertisement

Answer

token is in the accessTokenResponse object, so :

echo $result->accessTokenResponse->token;
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement