[英]I don't get a JSON response while using PHP curl
我正在尝试调用GitHubAPI,但是当我执行curl_exec()时,响应是一个简单的字符串。 我想要一个JSON响应。 我的代码如下:
if(isset($_GET['code']))
{
global $CLIENTID, $CLIENTSECRET;
$CODE = $_GET['code'];
$postfields = array('client_id' => $CLIENTID, 'client_secret' => $CLIENTSECRET, 'code' => $CODE);
$json_fields = json_encode($postfields);
$ch = curl_init("https://github.com/login/oauth/access_token");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
//curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type"=>"x-www-form-urlencoded", "Accept"=>"application/json"));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
$gitResponse = curl_exec($ch);
curl_close ($ch);
if($gitResponse)
{
echo var_dump($gitResponse);
}
else
{
echo "Error";
}
}
else
{
echo '<a href="https://github.com/login/oauth/authorize?client_id='.$CLIENTID.'" title="Login with Github">
LOGIN
</a>';
}
我已经尝试过使用CURLOPT_HTTPHEADER,但是它没有用,所以我发表了评论。 我收到的内容很好,但是它是字符串而不是JSON响应,因此我无法使用响应的字段。
谢谢!
将此添加到您的代码:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
这将请求服务器返回JSON字符串,然后您可以将其转换为数组以使用:
if($gitResponse)
{
$result = json_decode($gitResponse,true);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.