json_decode curl 反序列化错误
json_decode deserialization error with curl
我创建了一个运行良好的 Rest API,但我注意到一件奇怪的事情。为了反序列化客户端发送的内容,我使用以下代码:
var_dump(json_decode(file_get_contents("php://input"), true));
如果我使用 POSTMAN
(Chrome 分机)发送请求,一切正常,请参阅:
但如果我将 curl
与 MINGW64
一起使用,我将得到 NULL
:
现在,在这两种情况下,我都检查了这段代码的编码类型:
$content = file_get_contents("php://input");
$encode = mb_detect_encoding($content, "auto");
$json = mb_convert_encoding($content, $encode);
var_dump($json);
和这个returnsUTF-8
我不明白为什么,使用 curl MINGW64
,控制台无法工作,但使用扩展,或者正在工作。 happeni.g 是什么?
更新
我执行了这个函数:json_last_error()
,它返回了 5
。在这个site上,看到数字对应一个错误:
5 = JSON_ERROR_UTF8
但是我不知道哪里出了问题。
由于您要在正文中提交 JSON 数据,因此您需要告诉服务器内容类型,否则 cURL 会将其作为 application/x-www-form-urlencoded
.
发送
此外,任何 UTF-8 字符都需要以 \uXXXX
格式编码才能具有有效的 JSON 字符串。
尝试:
curl -i -H "token: company" \
-H "Content-type: application/json" \
-d '{"Code": "R89d", "Descri": "Questo \u00E8 un test"}' \
-X PUT http://localhost/api/customer/add
编辑:
不确定您从什么开始,但您可以使用以下两个命令为 cURL 提供正确的 JSON 字符串。
var=$(php -r 'echo json_encode(["Code" => "R89d", "Descri" => "Questo è un test"]);')
curl -v -H "Content-type: application/json" -d "$var" http://sandbox/test.php
将编码转换为 utf-8 对我有用。
$retorno_transaction = mb_convert_encoding($retorno_transaction, 'UTF-8');
我创建了一个运行良好的 Rest API,但我注意到一件奇怪的事情。为了反序列化客户端发送的内容,我使用以下代码:
var_dump(json_decode(file_get_contents("php://input"), true));
如果我使用 POSTMAN
(Chrome 分机)发送请求,一切正常,请参阅:
但如果我将 curl
与 MINGW64
一起使用,我将得到 NULL
:
现在,在这两种情况下,我都检查了这段代码的编码类型:
$content = file_get_contents("php://input");
$encode = mb_detect_encoding($content, "auto");
$json = mb_convert_encoding($content, $encode);
var_dump($json);
和这个returnsUTF-8
我不明白为什么,使用 curl MINGW64
,控制台无法工作,但使用扩展,或者正在工作。 happeni.g 是什么?
更新
我执行了这个函数:json_last_error()
,它返回了 5
。在这个site上,看到数字对应一个错误:
5 = JSON_ERROR_UTF8
但是我不知道哪里出了问题。
由于您要在正文中提交 JSON 数据,因此您需要告诉服务器内容类型,否则 cURL 会将其作为 application/x-www-form-urlencoded
.
此外,任何 UTF-8 字符都需要以 \uXXXX
格式编码才能具有有效的 JSON 字符串。
尝试:
curl -i -H "token: company" \
-H "Content-type: application/json" \
-d '{"Code": "R89d", "Descri": "Questo \u00E8 un test"}' \
-X PUT http://localhost/api/customer/add
编辑:
不确定您从什么开始,但您可以使用以下两个命令为 cURL 提供正确的 JSON 字符串。
var=$(php -r 'echo json_encode(["Code" => "R89d", "Descri" => "Questo è un test"]);')
curl -v -H "Content-type: application/json" -d "$var" http://sandbox/test.php
将编码转换为 utf-8 对我有用。
$retorno_transaction = mb_convert_encoding($retorno_transaction, 'UTF-8');