使用 PHP 回显 JSON 响应

Echo JSON response with PHP

我正在尝试回应格子 API 我的 JSON 回复的一部分。

代码如下:

$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);

这是回复:

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

我还收到 500 内部服务器错误,这是 echo $exchangeT 行的结果。我想获取 JSON 响应的 access_token 部分,对其进行回显以进行验证,并最终将其保存到数据库中。

只需将 true 作为第二个参数传递,如果第二个参数为 true,则 json_decode() returns 以数组格式而不是对象传递。

 $exchangeT = json_decode($exchangeToken, true);

如果您在 json_decode 中将 true 作为 second parameter 传递,那么您将得到 array 而不是 object 所以 改变这个

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

有关详细信息,请阅读 http://php.net/manual/en/function.json-decode.php

函数签名:

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

从函数定义可以看出,第二个参数$assoc默认为false。这个参数的作用(顾名思义)是当 TRUE 返回的对象将被转换为关联数组.

所以,在你的情况下,

$exchangeToken = json_decode($exchangeToken, true);

应该做你需要的。