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条)

报告相同问题?

悬赏问题

  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系