我有以下问题。此结构中的数据
$transfer = {stdClass} [4]
module = "Member"
action = "create"
token = null
params = {stdClass} [3]
username = "Test"
email = "test@test.com"
password = "Test"
必须是将vi REST发送到REST服务器。
因此,我使用json_encode ($object)对数据进行编码。解码后的对象如下所示:
{"module":"Member","action":"create","token":null,"params":{"username":"Test","email":"test@test.com","password":"Test"}}
出于测试目的,我对编码结果进行解码,以查看是否一切正常。这给了我正确的对象返回。
当我通过curl传输数据时,服务器接收到这个json_encoded数据:
{"module":"Member","action":"create","token":null,"params":{"username":"Test","email":"test@test.com" = ""
最后,json_decode($request)以以下错误结束:
json_decode() expects parameter 1 to be string, array given
它的curl代码是:
$curl = curl_init($url);
// prepare curl for Basic Authentication
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "$username:$password");
$curl_post_data = json_encode($postdata);
$test = json_decode($curl_post_data); // for testing
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data); <= $postdata = $transfer the object/array mentioned above
$curl_response = curl_exec($curl);
curl_close($curl);
怎么了?为什么无法在对REST服务器执行curl exec之后对编码数据进行解码?
发布于 2018-04-13 06:17:53
这是这个问题的神奇解决方案:
json_decode(key($object), true);
发布于 2018-04-12 05:17:15
据我所知,您发送的是$curl_post_data,这是CURLOPT_POSTFIELDS
中的json_encoded字符串。
CURLOPT_POSTFIELDS
接受数组而不是字符串。
所以你应该通过$curl_post_data['data'] = json_encode($postdata);
和接收数据json_decode($request['data'])
您正面临错误(json_decode()要求参数1为字符串,给定的数组),因为在传递字符串时$request为空
https://stackoverflow.com/questions/49788318
复制