Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

php

curl

$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

like image 226
Manoj Sreekumar Avatar asked Oct 28 '25 21:10

Manoj Sreekumar


2 Answers

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

like image 131
Aram Kocharyan Avatar answered Oct 30 '25 11:10

Aram Kocharyan


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);
like image 35
Slipstream Avatar answered Oct 30 '25 13:10

Slipstream