I am trying to use curl as below code snippet. I already tried all options i could search for the similar issue. have added all setopt options availabale but still i get response as 1. I am trying post request to server and expecting json response. What am I missing?
$logger->info('url:'.$service_url);
$curl = curl_init();
$curl_post_data = array(
'username' => 'user1',
'password' => 'welcome'
);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS,$curl_post_data);
curl_setopt($curl, CURLOPT_URL, $service_url);
curl_setopt($curl, CURLOPT_HTTPGET, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl,CURLOPT_POST, 1);
curl_setopt($curl,CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl,CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl,CURLOPT_CONNECTTIMEOUT ,3);
curl_setopt($curl,CURLOPT_TIMEOUT, 20);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Accept: application/json'
));
$curl_response = curl_exec($curl);
if ($curl_response === false) {
$info = curl_getinfo($curl);
curl_close($curl);
die('error occured during curl exec. Additioanl info: ' . var_export($info));
}
curl_close($curl);
$logger->info('curl_response 11:'.print_r($curl_response));
$decoded = json_decode($curl_response,JSON_PRETTY_PRINT);
if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') {
die('error occured: ' . $decoded->response->errormessage);
}
$logger->info('response ok!');
$logger->info('decoded:'.print_r($decoded));
Updated for solution: as suggested just used print_r($curl_response, true) to log the response, and used print_r($decoded['orderId']) to get the specific values.
print_r()
prints its output, it doesn't return it. In order to store the output of a call to print_r()
in a variable, or send it to a logger or whatnot, you need to pass a truthy value as the second parameter.
$x = print_r($foo); // prints formatted $foo and returns true
$x = print_r($foo, true); // prints nothing and returns formatted $foo
Note: Since you've set CURLOPT_RETURNTRANSFER
to true, the call to curl_exec()
will already return a string. There's really no need to pass that through print_r()
, just dump the string.
Also note: You'll want to verify that json_decode()
doesn't return null
. And you'll likely also want to verify that the HTTP status code is 200 (which you can do via curl_getinfo()
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.