从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}
doumu5023
doumu5023 那个人也不行。返回相同的结果{“access_token”:“bc6f5997-221a-381d-9f5b-aa3bb380037d”,“refresh_token”:“7bf1ddad-d696-3d83-a524-37dac002164a”,“scope”:“default”,“token_type”:“承载”,“expires_in”:3600}。谢谢
大约 2 年之前 回复
douzhangbao2187
douzhangbao2187 您正在解码为关联数组(json_decode的第二个参数设置为true)。将其视为一个:$result['access_token']
大约 2 年之前 回复
duanli4146
duanli4146 这是$access_token=$result->access_token的结果;我没有线更新了这个问题。谢谢
大约 2 年之前 回复
douzi2749
douzi2749 在json_decode检查json_last_error和json_last_error_message之后这是什么
大约 2 年之前 回复
douluohan3403
douluohan3403 嗨@Andreas删除了它但仍然无法提取访问令牌。$result=json_decode($result,true);$access_token=$result->access_token;
大约 2 年之前 回复
doudou7361
doudou7361 这是$access_token=$result->access_token的响应;
大约 2 年之前 回复
doudao6529
doudao6529 为什么Json字符串后面有1?这将导致json_decode不起作用我相信。编辑:没有1它工作正常。3v4l.org/Y0KKX
大约 2 年之前 回复

1个回答

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);
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问