4
$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

1
  • 1
    Your output is all content with headers and though it is not valid JSON. Commented Mar 1, 2013 at 14:23

2 Answers 2

13

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

Sign up to request clarification or add additional context in comments.

1 Comment

php.net/manual/en/function.curl-setopt.php has more info about curl options, including CURLOPT_HEADER.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.