我正在尝试不使用facebook login
访问sdk
的{{1}},这就是为什么我从php
获取access_token的原因,如下所示:
facebook
但是我只想要array(1) { ["{"access_token":"xxxxxxxxxxxxxxx","token_type":"bearer","expires_in":543543581}"]=> string(0) "" }
这样的access_token => "xxxxxxxxxxx"
我已经尝试过了:
$access_token['access_token'];
或 parse_str($ access_token,$ token_array);
但没有运气!
我该怎么办?
if(isset($access_token['access_token']) || array_key_exists('access_token', $access_token))
答案 0 :(得分:3)
get_access_token
中将parse_str
更改为json_decode
;
parse_str('{"access_token":"xxxxxxxxxxxxxxx","token_type":"bearer","expires_in":543543581}', $res);
print_r($res);
输出
Array
(
[{"access_token":"xxxxxxxxxxxxxxx","token_type":"bearer","expires_in":543543581}] =>
)
解析字符串只是将其当作字符串并对待,就像它是URL查询字符串example.com?foo
的一部分一样:
parse_str('foo=bar', $res);
print_r($res);
parse_str('foo', $res);
print_r($res);
输出
//parse_str('foo=bar', $res);
Array
(
[foo] => bar
)
//parse_str('foo', $res);
Array
(
[foo] =>
)
就像foo
将成为[foo => bar]
中的键一样,您的字符串也将成为此处的键。
parse_str 解析已编码的字符串,就好像它是通过URL传递的查询字符串一样,并在当前范围(或提供结果的数组)中设置变量。
使用Json解码
print_r(json_decode('{"access_token":"xxxxxxxxxxxxxxx","token_type":"bearer","expires_in":543543581}', true));
输出
Array
(
[access_token] => xxxxxxxxxxxxxxx
[token_type] => bearer
[expires_in] => 543543581
)
所以:
function get_access_token(){
$app_secret = "bbbbbbbbbbbbb";
$app_id = "aaaaaaaaaaaaaa";
$redirect_uri = urlencode("https://localhost/firefly/Oauth/facebook");
$code = $_REQUEST["code"];
$response = file_get_contents("https://graph.facebook.com/oauth/access_token?client_id=".$app_id."&redirect_uri=".$redirect_uri."&client_secret=".$app_secret."&code=".$code);
$res = json_decode($response, true);
//return false or the access_token
return isset($res['access_token']) ? $res['access_token'] : false;
//OR
return $res; //return the whole response
//---------- old code ---------
//parse_str($response, $access_token);
//return $access_token;
}
答案 1 :(得分:2)
因此,您将获得作为数组项的响应,其中关键是JSON数据和空值?
您的回应很丑陋,但这就是您本可以获取价值的方式:
<?php
$response = [
'{"access_token":"xxxxxxxxxxxxxxx","token_type":"bearer","expires_in":543543581}' => '',
];
$response_key = \array_keys($response)[0];
$response_array = \json_decode($response_key, true);
$access_token = $response_array['access_token'];
echo $access_token;
?>