Atasha Atasha - 1 month ago 8
JSON Question

How to parse ONLY the JSON value returned by CURL in PHP?

I am able to successfully make a send POST values through CURL but I can't seem to figure out how to get the only the JSON code it returns.

Here is a part of my code:

try {
$curl = curl_init($url);

if (FALSE === $curl)
throw new Exception('failed to initialize');

curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json")
);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));

$message = curl_exec($curl);

if (FALSE === $message)
throw new Exception(curl_error($curl), curl_errno($curl));

$response = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$error = $message;

var_dump($error);
curl_close($curl);

} catch(Exception $e) {
trigger_error(
sprintf(
'Curl failed with error #%d: %s',
$e->getCode(), $e->getMessage()
),
E_USER_ERROR
);
}


I am able to get the correct value for the $response variable but the returned message gives me:

string(253) "HTTP/1.1 400 Bad Request Cache-Control: no-cache Pragma: no-cache Content-Type: application/json; charset=utf-8 Expires: -1 Server: Microsoft-IIS/8.5 Date: Sun, 02 Jul 2017 17:47:34 GMT Content-Length: 38 {"Message":"Email is already in used"}"


when I try to use var_dump. What I am aiming to store for me error message variable it the value for Message that is in {"Message":"Email is already in used"}

Any tips?

Thanks so much!

Answer Source
HTTP/1.1 400 Bad Request Cache-Control: no-cache Pragma: no-cache Content-Type: application/json; charset=utf-8 Expires: -1 Server: Microsoft-IIS/8.5 Date: Sun, 02 Jul 2017 17:47:34 GMT Content-Length: 38

Are the headers returned by the cURL request.
You'll have to set CURLOPT_HEADER to FALSE (0) to remove the headers from the output:

curl_setopt($curl, CURLOPT_HEADER, 0);

As stated by the documentation when CURLOPT_HEADER is TRUE headers will be included in the output.