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 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)