user3916353
user3916353

Reputation: 21

PHP: json_decode returns NULL when reading using curl

I need to decode a JSON fragment so that I can start manipulating JSON, but json_decode returns null, when I try to read using curl.

PHP code:

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

The output was as follows in 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

The comments in the PHP code will show everything that I've tried and all the available solutions already.

Upvotes: 0

Views: 2141

Answers (2)

Phantom
Phantom

Reputation: 1700

Your $output variable contains header, you should use the following option:

curl_setopt($ch, CURLOPT_HEADER, false);

or get headers length and remove it from output (so only body remains):

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

Upvotes: 2

Girish
Girish

Reputation: 12127

CURLOPT_HEADER option use false, because header is coming with response

curl_setopt($ch, CURLOPT_HEADER, false);

Upvotes: 6

Related Questions