Manoj Sreekumar
Manoj Sreekumar

Reputation: 738

json_decode is returning a null object after I use CURL to obtain JSON data

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, array('Content-type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($ch);
var_dump($output);
$json_array = json_decode($output, true);

var_dump(curl_error($ch));

curl_close($ch);

var_dump($json_array);

VARDUMP for $output

string(267) "HTTP/1.1 200 OK Date: Fri, 01 Mar 2013 14:16:57 GMT Server: Apache/2.4.3 (Win32) OpenSSL/1.0.1c PHP/5.4.7 X-Powered-By: PHP/5.4.7 cache-control: no-cache x-debug-token: 5130b85a178bd Transfer-Encoding: chunked Content-Type: application/json {"name":"manoj"}"

VARDUMP for curl_error($ch)

string(0) ""

VARDUMP for $json_array

NULL

Upvotes: 4

Views: 7142

Answers (2)

Slipstream
Slipstream

Reputation: 14762

If for any reason you have to maintain the CURLOPT_HEADER option, you can use the following:

$output = curl_exec($ch);  

$json_data = mb_substr($output, curl_getinfo($ch, CURLINFO_HEADER_SIZE));  
$data = json_decode($json_data);

You can use the CURLOPT_HEADER option to check the return code 200, 404 etc...

$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

Upvotes: 2

Aram Kocharyan
Aram Kocharyan

Reputation: 20431

NULL is returned if the json cannot be decoded

You don't want to return the header in the body of the curl_exec, so you'll need:

curl_setopt($ch, CURLOPT_HEADER, false)

http://php.net/manual/en/function.json-decode.php

Upvotes: 13

Related Questions