【发布时间】:2019-10-25 10:14:27
【问题描述】:
简介
所以我试图将表单值作为查询字符串发送到 API。 API 需要这样的查询字符串:
&name=Charles+Hansen&email=example@email.com&locations=23433&locations=23231&propertyTypes=APARTMENT&propertyTypes=TOWNHOUSE&message=test"
正如您所见,根据用户在表单中选择的属性类型或位置的数量,有多个“属性类型”和“位置”。因此,我将所有 $_POST 数据存储在一个看起来像这样的多维数组中,因为我显然不能有多个具有相同名称“propertyTypes”或“locations”的键:
Array
(
[name] => Charles Hansen
[email] => example@email.com
[locations] => Array
(
[0] => 23433
[1] => 23231
)
[propertyTypes] => Array
(
[0] => APARTMENT
[1] => TOWNHOUSE
)
[message] => test
)
cURL 不支持多维数组,因此我先自己构建查询,然后再使用它。这是我的 cURL 函数:
function sg_order($post_fields) {
if($post_fields) {
$query = http_build_query($post_fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://example.com/order?orgKey=' . constant('ORG_KEY'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Content-Length: ' . strlen($query))
);
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if(curl_errno($ch)) {
error_log('Curl error: ' . curl_error($ch) . $result);
}else{
error_log('Curl response: ' . $status);
}
curl_close($ch);
return $result;
}
}
orgKey 是验证的必需参数。
问题
我的问题是,$query = http_build_query($post_fields); 构建的查询包含嵌套数组的键([0]、[1] 等)。 $query 的结果如下所示:
&name=Charles+Hansen&email=example@email.com&locations[0]=23433&locations[1]=23231&propertyTypes[0]=APARTMENT&propertyTypes[1]=TOWNHOUSE&message=test"
如何删除键([0]、[1] 等),以使查询看起来完全符合 API 的预期?
其他信息
- 我无法控制 API
- 我不发送文件,因此解决方案不必处理文件
【问题讨论】:
-
将其转换为 json 而不是尝试发送
-
@YasinPatel 我可以试试,但据我所知,他们的 API 只接受 URL 编码的字符串。如果我将其作为 json 发送,是否会因为 HTTPHEADER 设置而通过 curl 自动转换为 URL 编码字符串?
-
如果您不想编写自己的 http_build_query 版本,那么我建议您修改 php.net/manual/en/function.http-build-query.php#111819,将匹配项替换为空字符串而不是
'%5B%5D'。 -
@04FS 是的,行得通!谢谢!如果您做出回答,我会接受它作为解决方案。