PHP:json_decode在使用curl读取时返回NULL

PHP:json_decode在使用curl读取时返回NULL,php,curl,json,Php,Curl,Json,我需要解码一个JSON片段,以便开始操作JSON,但是当我尝试使用curl读取时,JSON\u decode返回null PHP代码: $username='xx'; $password='xx'; $headers = array( 'Content-Type:application/json', 'accept: application/json', 'Authorization: Basic '. base64_encode($username.":".$password)

我需要解码一个JSON片段,以便开始操作JSON,但是当我尝试使用curl读取时,
JSON\u decode
返回
null

PHP代码:

$username='xx';
$password='xx';
$headers = array(
'Content-Type:application/json',
    'accept: application/json',
    'Authorization: Basic '. base64_encode($username.":".$password),
    'x-myobapi-exotoken: xx'
);

$url = "http://example.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERPWD, $username.":".$password);
curl_setopt($ch, CURLOPT_URL, $url);
$output = curl_exec($ch);

echo '<pre>';
echo $output; //works fine till here

echo "<br><br>Break <br>";

//all the commented part has been tried

//$my_array = json_decode(str_replace ('\"','"', $output), true);
//var_dump($my_array);
// print_r(json_decode(substr($output,3))); //tried already

$obj = json_decode($output);
var_dump($obj);//gives NULL
print $obj->{'firstname'};

curl_close($ch);

PHP代码中的注释将显示我尝试过的所有内容以及所有可用的解决方案。

CURLOPT_HEADER
选项使用
false
,因为
HEADER
将随响应而来

curl_setopt($ch, CURLOPT_HEADER, false);

$output
变量包含标题,应使用以下选项:

$info   = curl_getinfo($ch);
$result = substr($output, $info['header_size']);
或者获取标题长度并将其从输出中删除(因此只保留正文):


$output
是有效的JSON吗?你能通过一些在线JSON验证程序来检查它吗?
JSON\u last\u error
说了什么?@mtores你可以对这两个答案进行投票,因为它们都很快;)谢谢!我整天都在拔头发!你救了我一天!
curl_setopt($ch, CURLOPT_HEADER, false);
$info   = curl_getinfo($ch);
$result = substr($output, $info['header_size']);