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

时间:2014-08-12 11:04:17

标签: php curl json

我需要解码一个JSON片段,以便我可以开始操作JSON,但当我尝试使用curl读取时json_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);

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代码中的注释将显示我尝试过的所有内容以及所有可用的解决方案。

2 个答案:

答案 0 :(得分:5)

CURLOPT_HEADER选项使用false,因为header即将回复

curl_setopt($ch, CURLOPT_HEADER, false);

答案 1 :(得分:2)

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

curl_setopt($ch, CURLOPT_HEADER, false);

或获取标题长度并将其从输出中删除(因此只剩下正文):

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