du9826
2018-10-18 19:25 阅读 248

从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 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);
    
    点赞 评论 复制链接分享

相关推荐