在PHP中通过curl来POST多维JSON参数

问题描述 投票:0回答:1

我不知道如何正确编码这个多维 JSON 记录来查询在线记录集合:

{
    "conditions" : [
    {
     "fullpath" : {
        "operator" : "starts_with",
        "value" : "/Destination Structure Test/2-Thinking Outside the Borders. Library Leadership in a World Community/"
        }
    },
    {
        "filename" : {
            "operator" : "eq",
            "value" : "ThinkingOutsideTheBorders.pdf"
        }
    }   
    ]
}

能够发布它。我收到 404 错误,我认为这意味着我已成功正确进行身份验证,但无法传递这些搜索参数。我看过其他代码示例,但显然我只是缺少一个主要概念。

我尝试用 PHP 对其进行建模:

    <?php

    $apiUrl = 'https://the_url_I_am_using';

    $bearerToken = 'wombats';

    $ch = curl_init($apiUrl);

$data = array();
$data["conditions"] = array();
$conditions["fullpath"] = array();
$conditions["filename"] = array();

$fp = array();
$fp["operator"] = "starts_with";
$fp["value"] = "/Destination Structure Test/2-Thinking Outside the Borders/";
$conditions["fullpath"][] = $fp;

$fn = array();
$fn["operator"] = "eq";
$fn["value"] = "ThinkingOutsideTheBorders.pdf";
$conditions["filename"][] = $fn;

$data = http_build_query($data);
$payload = json_encode(array("user" => $data));

curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  // Return the response as a string
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $bearerToken",  // Set the Authorization header
    "Content-Type: application/json",      // Specify that we are sending/receiving JSON
]);

$response = curl_exec($ch);

if(curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);  // If there's an error, print it
} else {
    // Print the response
    echo 'Response: ' . $response;
}

// Close the cURL session
curl_close($ch);
php json curl
1个回答
0
投票

您已经知道结构应该是什么,只需将其从

{"key": "value"}
JSON 语法更改为
["key" => "value"]
PHP 语法即可。

$data = [
    "conditions" => [
        [
            "fullpath" => [
                "operator" => "starts_with",
                "value" => "/Destination Structure Test/2-Thinking Outside the Borders. Library Leadership in a World Community/"
            ]
        ],
        [
            "filename" => [
                "operator" => "eq",
                "value" => "ThinkingOutsideTheBorders.pdf"
            ]
        ]   
    ]
]
© www.soinside.com 2019 - 2024. All rights reserved.