[英]PHP Array JSON encoding and decoding in REST not working
我有以下问题。 此数据在此结构中
$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_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);
怎么了? 为什么在curl执行到REST Server之后无法解码编码的数据?
这是解决该问题的神奇方法:
json_decode(key($object), true);
据我了解,您正在发送$ curl_post_data,它是CURLOPT_POSTFIELDS
的json_encoded字符串。
CURLOPT_POSTFIELDS
接受数组而不是字符串。
因此,您应该传递$curl_post_data['data'] = json_encode($postdata);
并接收数据json_decode($request['data'])
您面临错误(json_decode()期望参数1为字符串,给定数组),因为传递字符串时$ request为空
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.