我能够通过 CURL 成功发送 POST 值,但我似乎无法弄清楚如何获取它返回的唯一 JSON 代码。
这是我的代码的一部分:
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
);
}
我能够获得 $response 变量的正确值,但返回的消息给了我:
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"}"
当我尝试使用 var_dump 时。我的目标是为我存储错误消息变量,它是 {"Message":"Email is already in used"} 中 Message 的值
有小费吗?
非常感谢!
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
是 cURL 请求返回的标头。
您必须设置CURLOPT_HEADER
为FALSE
( 0
) 才能从输出中删除标题:
curl_setopt($curl, CURLOPT_HEADER, 0);
正如所陈述的文档时CURLOPT_HEADER
是TRUE
报头将被包含在输出中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句