Search code examples
phpjsonplaid

Echo JSON response with PHP


I am trying to echo a portion of my JSON response from the Plaid API.

Here is the code:

$data = array(
            "client_id"=>"test_id",
            "secret"=>"test_secret",
            "public_token"=>"test,fidelity,connected");
        $string = http_build_query($data);

    //initialize session
    $ch=curl_init("https://tartan.plaid.com/exchange_token");

    //set options
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    //execute session
    $exchangeToken = curl_exec($ch);
    echo $exchangeToken;
    $exchangeT = json_decode($exchangeToken);
    echo $exchangeT['access_token'];
    //close session
    curl_close($ch);

Here is the response:

{ "sandbox": true, "access_token": "test_fidelity" }

I also get a 500 Internal Server Error, which results from the echo $exchangeT line. I want to take the access_token portion of the JSON response, echo it to verify, and eventually save it to a database.


Solution

  • If you pass true as second parameter in your json_decode then you will get an array instead of object so change this

         $exchangeT = json_decode($exchangeToken, true);
    // it wii output as $exchangeT = array('sandbox'=>true,'access_token'=>'test_fidelity');
            echo $exchangeT['access_token'];
    

    for more info read http://php.net/manual/en/function.json-decode.php