Php 如何在curl POST请求中执行json查询
我试图在curl POST命令中将以下查询发送到API:Php 如何在curl POST请求中执行json查询,php,json,curl,Php,Json,Curl,我试图在curl POST命令中将以下查询发送到API: { "query": [ { "code": "series1", "selection": { "filter": "item", "values": [ "1", "2", "3" ] } }, { "code": "series2", "s
{
"query": [
{
"code": "series1",
"selection": {
"filter": "item",
"values": [
"1",
"2",
"3"
]
}
},
{
"code": "series2",
"selection": {
"filter": "item",
"values": [
"1",
"2",
"3"
]
}
}
],
"response": {
"format": "json"
}
}
到目前为止,我让它工作的唯一方法是使用在线转换器将我的查询硬编码如下:
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\n \"query\": [\n {\n \"code\": \"series1\",\n \"selection\": {\n \"filter\": \"item\",\n \"values\": [\n \"1\",\n \"2\",\n \"3\"\n ]\n }\n },\n {\n \"code\": \"series2\",\n \"selection\": {\n \"filter\": \"item\",\n \"values\": [\n \"1\",\n \"2\",\n \"3\"\n ]\n }\n }\n ],\n \"response\": {\n \"format\": \"json\"\n }\n}\n\n}");
是否有更好的方法将查询存储为更可读的格式的变量,并将此变量传递给curl_setopt 使用数组和json编码:
$data = ["query" => "...", "response" => ["format" => "json"]];
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
upd:您可以尝试这个简单的解决方案
function curl(string $method, string $url, array $data = [])
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
if ('POST' === $method) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
$response = curl_exec($ch);
curl_close($ch);
return json_decode($response, true);
}
然后:
curl('POST', 'http://myApi/foo/bar', ['a' => 'b']);
是否有一种简单的方法可以将查询测试转换为示例中的数组?@FilipBlaauw
$data=var_导出(json_解码(“{”查询“:[{”foo:“bar”}]}',true)代码>