从JSON php curl中提取数据:json_decode不起作用

时间:2018-10-18 19:25:34

标签: php json curl

我有以下代码:

<?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);
?>

它返回json结果后的样本,但返回json_decode却不返回访问令牌。 curl_setopt($ curl,CURLOPT_RETURNTRANSFER,1);不返回下面的令牌。感谢你们对我的帮助。

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

1 个答案:

答案 0 :(得分:0)

由您的答案所鼓舞-@Andreas和@YvesLeBorg,我重新编写了代码并得到了我想要的。我要用这个来帮助别人。谢谢。

<?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);