我写了一个应该打印json调用响应的php代码。但我得到NULL输出。我已经检查过我的json调用从restclient工作正常。
这是我的代码
<?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);
?>
提前致谢。
答案 0 :(得分:1)
尝试:
$responseData = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new \RuntimeException('Invalid JSON.');
}
答案 1 :(得分:0)
好吧所以我已经解决了我的问题并重新编写了代码。我实际上没有在json字段中提供正确形式的用户名和密码,这实在是一个愚蠢的错误。 我在这里提供更新的代码 `
$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;
?>`
谢谢大家。