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


PHP: json_decode returns NULL when reading using curl

我需要解码JSON片段,以便我可以开始操作JSON,但是json_decode返回null,当我尝试使用curl读取时。

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);

在Google Chrome中输出如下:

Output:
HTTP/1.1 200 OK
Content-Length: 675
Content-Type: application/json; charset=utf-8
Server: Microsoft-HTTPAPI/2.0
Link: ; rel="describedBy"; method="PUT",; rel="describedBy"; method="POST"
Date: Tue, 12 Aug 2014 07:30:48 GMT
{
  "jobtitle": null,
  "firstname": "XYZ",
  "lastname": "XYZ",
  "fullname": "XYZ XYZ",
  "directphonenumber": null,
  "mobilephonenumber": null,
  "email": null,
  "postaladdress": {
    "line1": "",
    "line2": "",
    "line3": "",
    "line4": "",
    "line5": ""
  },
  "postalcode": "",
  "deliveryaddress": {
    "line1": "",
    "line2": "",
    "line3": "",
    "line4": "",
    "line5": "",
    "line6": ""
  },
  "advertsourceid": 0,
  "active": true,
  "optoutemarketing": false,
  "salespersonid": 10,
  "defaultcompanyid": null,
  "extrafields": [],
  "id": 129,
  "href": "http://example.com"
}
Break
NULL
Reply
Forward

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

CURLOPT_HEADER选项使用false,因为header正在响应

curl_setopt($ch, CURLOPT_HEADER, false);

您的$output变量包含header,您应该使用以下选项:

curl_setopt($ch, CURLOPT_HEADER, false);

或者获取报头长度并将其从输出中删除(因此只保留正文):

$info   = curl_getinfo($ch);
$result = substr($output, $info['header_size']);