duanli9591 2017-11-02 15:10
浏览 50
已采纳

php无法解码json对象

I have this json object that I want to get the access_token but its refusing i have no idea why . This is the response I want the access_token

{
        "access_token": "Alhq74lVl5GAOVAZrprOGSS1Gj73",
        "expires_in": "3599"
    }

This is the code

function generateToke() {
// $url = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
   $url = 'https://api.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';
   $curl = curl_init();
   curl_setopt($curl, CURLOPT_URL, $url);
   $credentials = base64_encode('qniogqzdbIskIQt9nxgxG1wSBkzgUqN0:XUjxWzQY3WTndqHh');
   curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . $credentials)); //setting a custom header
   curl_setopt($curl, CURLOPT_HEADER, false);
   curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

   $curl_response = curl_exec($curl);
   $result = json_decode($curl_response);


   $token = $result->access_token;
   echo $token;

}

getting the same error

the above code is still displaying to me the json but i want to get only the Alhq74lVl5GAOVAZrprOGSS1Gj73

  • 写回答

2条回答 默认 最新

  • duandunzhuo3234 2017-11-02 15:14
    关注

    You're not accessing the access_token property of the resulting object, you try to access a property that is named in the not defined variable $access_token;.

    So just remove the $-sign and it shoudl work:

    $token = $result->access_token;
    

    Furthermore you're missing a curl option to return the content:

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    

    Without this option set to true you're not retrieving the response from the curl_exec call.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 帮我调试idea基于spring boot项目
  • ¥15 es 7.17.20版本生成时间戳
  • ¥15 wpf dategrid表头排序图标自定义
  • ¥15 分析下图所示同步时序逻辑电路的逻辑功能。
  • ¥15 halcon联合c#遇到了问题不能解决
  • ¥15 xshell无法连接提示ssh服务器拒绝密码
  • ¥15 AT89C52单片机C语言关于串口通信的位操作
  • ¥20 需要步骤截图(标签-服务器|关键词-map)
  • ¥50 gki vendor hook
  • ¥15 灰狼算法和蚁群算法如何结合