du9826 2018-10-18 19:25
浏览 290
已采纳

从JSON php curl中提取数据:json_decode无法正常工作

I have the following code:

<?php 

$consumerKey = '';
$consumerSecret = '';
$url = '';

$data = array(
'grant_type'  => 'password',
    'username'    => '',
    'password'    => ''
);


$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json','Accept-Language: en_US'));
curl_setopt($curl, CURLOPT_USERPWD, $consumerKey.':'.$consumerSecret);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
    $result = curl_exec($curl);
    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    $result = json_decode($result);
    curl_close($curl);
?>

It returns the sample following json result, but not the access token despite the json_decode. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); does not return the token below. Thank you for helping me.

{"access_token":"ffdd8dfb-2013-32ee-bc3e-dc5689d6c8fb","refresh_token":"7bf1ddad-d696-3d83-a524-37dac002164a","scope":"default","token_type":"Bearer","expires_in":3600}
  • 写回答

1条回答

  • duan5801 2018-10-19 08:34
    关注

    Buoyed by your answers - @Andreas and @YvesLeBorg, I redid the code and got what I want. I am putting this to help someone else. Thank you.

    <?php 
    
    $consumerKey = '';
    $consumerSecret = '';
    $url = '';
    $curl = curl_init($url);
    $data = array(
        'grant_type'  => 'password',
        'username'    => '',
        'password'    => ''
    );
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json','Accept-Language: en_US'));
    curl_setopt($curl, CURLOPT_USERPWD, $consumerKey.':'.$consumerSecret);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE);
        $result = curl_exec($curl);
        $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        $result = json_decode($result);
        $access_token = $result->access_token;
    echo $access_token;
        curl_close($curl);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题