PHP cURL API 嵌套数组问题和 http_build_query

PHP cURL API problem with nested arrays and http_build_query

获得了在终端上运行的 cURL 代码以更改在线 SIP 服务上转发的 phone 号码(无法访问 REST API 服务器端):

curl --request PUT --header "Accept: application/json" --header "Authorization: Basic abcdefABCDEFmysecretkey123456" -d '{"forwardings":[{"destination":"+447979123456","timeout":0,"active":true}]}' --header "Content-type: application/json" https://api.sipgate.com/v2/w0/phonelines/p0/forwardings

然而,我在 PHP 中复制此代码的努力导致 {"error":"cannot parse content"} 响应:

$ch = curl_init();
$churl='https://api.sipgate.com/v2/w0/phonelines/p0/forwardings';
$chdata = array(
    'forwardings' => array(
        'destination' => '+447979123456',
        'timeout' => 0,
        'active' => true
    )
);
$chdata2 = http_build_query($chdata);
curl_setopt($ch, CURLOPT_URL, $churl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "Content-type: application/json",
    "charset: utf-8",
    "Accept: application/json",
    "Authorization: Basic abcdefABCDEFmysecretkey123456"
));
curl_setopt($ch, CURLOPT_POSTFIELDS, $chdata2);
$json = curl_exec($ch);
echo $json;
curl_close($ch);

我错过了什么?

由于内容类型设置为 JSON,它期望您传递的数据经过 json 编码。

尝试替换

$chdata2 = http_build_query($chdata);

$chdata2 = json_encode($chdata);

更新@CBroe 评论

将 $chdata 数组更改为

$chdata = array(
    'forwardings' => array(
        array(
            'destination' => '+447979123456',
            'timeout' => 0,
            'active' => true
        )
    )
);

[from comments} I might be wrong, but I think json_encode does not properly handle nested arrays?

json_encode 处理得很好,只是您没有提供正确的输入数据结构。

您的数据中缺少一级数组。 'forwardings' => array(...) 需要 'forwardings' => array( array(...) )


BTW/FYI/for 任何可能需要它的人:获取 所需数据结构的简单方法,已经以可用 PHP 代码的形式出现,基于现有的 JSON,将是 var_export 和 json_decode 的组合:

var_export(json_decode('{"forwardings":[{"destination":"+447979123456","timeout":0,"active":true}]}', 1));

得到以下结果,

array (
  'forwardings' => 
  array (
    0 => 
    array (
      'destination' => '+447979123456',
      'timeout' => 0,
      'active' => true,
    ),
  ),
)

所以你可以在前面打一个 $chdata = ,在最后打一个 ;,然后就完成了。