【问题标题】:PHP Array JSON encoding and decoding in REST not workingREST中的PHP数组JSON编码和解码不起作用
【发布时间】:2018-09-22 02:53:50
【问题描述】:

我有以下问题。此结构中的数据

$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);

怎么了?为什么 curl exec 到 REST 服务器后无法解码编码数据?

【问题讨论】:

  • 请检查代码:- $object = '[{"module":"Member","action":"create","token":null,"params":{"username": "Test","email":"test@test.com","password":"Test"}}]'; $data = json_decode($object);字符串问题
  • 检查码 Sunny 是什么意思?我现在还添加了 curl 语句。

标签: php arrays json rest decoding


【解决方案1】:

据我了解,您发送的 $curl_post_data 是 CURLOPT_POSTFIELDS 中的 json_encoded 字符串。

CURLOPT_POSTFIELDS 接受数组而不是字符串。

所以你应该通过$curl_post_data['data'] = json_encode($postdata);

并接收数据json_decode($request['data'])

您正面临错误(json_decode() 期望参数 1 是字符串,给定数组)因为 $request 在您传递字符串时是空白的

【讨论】:

  • 负分不是来自我。我不知道为什么会这样,没有评论。请继续关注本主题。
  • 我想回答问题,这就是我要求提供 curl 数据的原因。我在编辑中回答了。我无法发表评论,因为我是新来的,这就是我回答问题的原因
  • @DewanshuSharma 您应该回答一些不同的问题,这些问题不需要您滥用答案字段,直到您得到代表发表评论为止。
  • $curl_post_data['data'] 不起作用,不会触发其余调用。
  • 您可以像这样传递数组或 url_encoded 字符串 'data='.urlencode(json_encode($postdata)) 现在您可以通过 $request['data'] 获取 $postdata 或添加此 curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' .strlen($postdata)));
【解决方案2】:

这是该问题的神奇解决方案:

json_decode(key($object), true);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多