PHP中使用curl POST多维JSON参数的编码问题求助
问题:POST请求多维JSON参数编码错误导致404
我不清楚如何正确编码以下多维JSON记录,以查询在线记录集合并通过POST请求发送,发送请求时遇到404错误,推测认证已成功,但搜索参数传递不正确。
目标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" } } ] }
我的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);
错误分析与修正方案
核心错误点:
- 数组结构构建错误:目标JSON中
conditions是一个数组,每个元素是独立的对象(分别包含fullpath或filename键),但你错误地将fullpath和filename作为同级键放在了一个数组里,结构完全不符。 - 误用
http_build_query:该函数用于生成URL编码的查询字符串,不适合构建JSON结构,且你后续将结果包裹在user键下,彻底偏离了目标格式。 - Payload结构错误:目标JSON的顶级键是
conditions,但你生成的Payload是{"user": ...},API无法识别参数。
修正后的代码:
<?php $apiUrl = 'https://the_url_I_am_using'; $bearerToken = 'wombats'; $ch = curl_init($apiUrl); // 构建与目标JSON完全匹配的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" ] ] ] ]; // 直接将数组编码为JSON作为Payload $payload = json_encode($data); curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, [ "Authorization: Bearer $bearerToken", "Content-Type: application/json", ]); $response = curl_exec($ch); if(curl_errno($ch)) { echo 'Error:' . curl_error($ch); } else { echo 'Response: ' . $response; } curl_close($ch);
关键修正说明:
- 直接构建与目标JSON结构完全一致的PHP多维数组,确保层级和键名匹配。
- 移除
http_build_query和多余的user包装,直接对正确的数组执行json_encode生成Payload。 - 保持请求头的
Content-Type: application/json不变,确保API能正确解析JSON格式的参数。
内容的提问来源于stack exchange,提问作者Andrew Bullen
相关产品推荐
相关产品推荐

