[英]json_decode deserialization error with curl
我创建了一个运行良好的 Rest API,但我注意到了一件奇怪的事情。 为了反序列化客户端发送的内容,我使用以下代码:
var_dump(json_decode(file_get_contents("php://input"), true));
如果我使用POSTMAN
(Chrome 扩展程序)发送请求,则一切正常,请参阅:
但是如果我将curl
与MINGW64
一起MINGW64
,我会得到NULL
:
现在,在这两种情况下,我都检查了此代码的编码类型:
$content = file_get_contents("php://input");
$encode = mb_detect_encoding($content, "auto");
$json = mb_convert_encoding($content, $encode);
var_dump($json);
这将返回UTF-8
我不明白为什么使用 curl MINGW64
,控制台不工作,但有扩展,或者正在工作。 怎么了?
更新
我已经执行了这个函数: json_last_error()
,它返回了5
。 在这个网站上,我看到这个数字对应一个错误:
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');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.