我知道这是一个非常愚蠢的问题,但我仍然要问这个因为它不起作用。
我正在调用API ...
$service_url = 'http://localhost:8888/ffmobile/signup';
$curl = curl_init($service_url);
$curl_post_data = array('email' => $this->params()->fromPost('email'), 'password' => $this->params()->fromPost('password'), 'userName' => $this->params()->fromPost('uname'));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl);
curl_close($curl);
当我打印$ curl_response时,输出如下
{"Error":{"name":"Email Unavailable","message":"Email is already taken. Please choose different email.","code":202},"status":"False","requestId":null}
输出是正确的,但是当我使用它时如下......
$response = json_decode($curl_response, TRUE);
我正在打印没有打印任何内容的$响应。
可能是什么问题?
有人能帮助我吗?
答案 0 :(得分:1)
试试这个例子:
<?php
$json = '{
"Error": {
"name": "Email Unavailable",
"message": "Email is already taken. Please choose different email.",
"code": 202
},
"status": "False",
"requestId": null
}';
$info = json_decode($json, true);
echo "Error - Name: {$info['Error']['name']}<br>";
echo "Error - Message: {$info['Error']['message']}<br>";
echo "Error - Code: {$info['Error']['code']}<br>";
echo "Status: {$info['status']}<br>";
echo "RequestId: {$info['requestId']}<br>";
?>
输出:
Error - Name: Email Unavailable
Error - Message: Email is already taken. Please choose different email.
Error - Code: 202
Status: False
RequestId:
答案 1 :(得分:0)
要检查解码是否正常,您可以运行此代码:
$json = '{"Error":{"name":"Email Unavailable","message":"Email is already taken. Please choose different email.","code":202},"status":"False","requestId":null}';
print_r(json_decode($json, TRUE));
如果你的代码中的isres是一个错误解码,json_decode将返回null,你可以检查这个,然后运行json_last_error()
答案 2 :(得分:0)
可能存在卷曲错误。如果是这种情况,curl_exec将返回false。 还要检查json_decode错误。
来源:http://php.net/manual/en/function.curl-error.php
$service_url = 'http://localhost:8888/ffmobile/signup';
$curl = curl_init($service_url);
$curl_post_data = array('email' => $this->params()->fromPost('email'), 'password' => $this->params()->fromPost('password'), 'userName' => $this->params()->fromPost('uname'));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl);
if($curl_response === false)
{
echo 'Curl error: ' . curl_error($curl);
}
else
{
$response = json_decode($curl_response, TRUE);
curl_close($curl);
if( is_null($response) ) {
echo 'json_decode error: ' . json_last_error();
} else {
// everything OK, do something with the response
}
}