Reputation: 45
I have written a php code that should print the response of a json call. But I am getting NULL output. I have checked my json call is working fine from a restclient.
Here is my code
<?php
$username = "user";
$password = "password";
$postData = array(
'username' => $username,
'password' => $password,
'msisdn' => "111111111"
);
$ch = curl_init('http://ip:<port>/xxx/yyy/zzz');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json'
),
CURLOPT_POSTFIELDS => json_encode($postData)
));
// Send the request
$response = curl_exec($ch);
// Check for errors
if($response === FALSE){
die(curl_error($ch));
}
// Decode the response
$responseData = json_decode($response, TRUE);
// Print the date from the response
echo $responseData['published'];
var_dump($responseData);
?>
Thanks in advance.
Upvotes: 0
Views: 445
Reputation: 45
okay so i have solved my problem and re-wrote the code. I was actually not providing the correct form of username and password in the json fields which is really a silly mistake. I am giving my updated code here `
$data = array("user" => "$username", "pass" => "$password", "msisdn" => "$msisdn");
$data_string = json_encode($data);
$ch = curl_init('http://ip:port/call_center/account/general');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
echo $result;
?>`
Thanks everyone.
Upvotes: 0
Reputation: 17061
Try:
$responseData = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \RuntimeException('Invalid JSON.');
}
Upvotes: 1