我正在测试一个cURL函数,以便在Foursquare上获取给定用户的访问令牌。以下函数以json格式将访问令牌打印到屏幕
{"access_token":"5B25GW5LF3L4W04PALHK32X5Z3YGNUUVDHM2TFBQOWZSQ121"}
我在提取访问令牌的值时遇到了问题。
这是我正在使用的功能:
function get_access_token($ code){
$url = "https://foursquare.com/oauth2/access_token";
$fields = array(
'client_id' => urlencode($this->client_id),
'client_secret' => urlencode($this->client_secret),
'grant_type' => 'authorization_code',
'redirect_uri' => urlencode($this->redirect_url),
'code' => $code
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
return var_dump($result) /* prints bool(true) */;
}
如何将此访问令牌存储在变量中?
谢谢
答案 0 :(得分:0)
默认情况下,curl_exec不会返回响应,而是返回指示成功或失败的值。请访问http://php.net/manual/en/function.curl-exec.php了解详情。
答案 1 :(得分:0)
再添加一行代码告诉curl将返回值传递回curl_exec和$ result变量:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
您可能还想检查数据返回时是否发生错误:例如:
$result = curl_exec($ch);
if (curl_errno($ch))
echo (curl_error($ch));
else
echo $result;
curl_close($ch);