PHP向API传递数组数据报错:destination字段非数组的问题排查
解决curl提交数组+文件时API无法识别数组字段的问题
嘿,你这是踩了个curl提交数据的常见坑!咱们来一步步拆解问题,找到解决办法:
问题根源
你把数据用json_encode()转成了JSON字符串发给API,但:
- curl默认会把
CURLOPT_POSTFIELDS的内容当成表单格式(multipart/form-data或application/x-www-form-urlencoded)处理,不会自动告诉API这是JSON; - API端用
$request->post('destination')是从表单数据里取值,根本没解析你发的JSON字符串,所以拿到的要么是整个JSON串,要么是空值,自然过不了数组校验; - 另外你还要上传文件,JSON格式本来就不支持直接传文件,这路子从一开始就走不通~
解决方案(推荐,适配文件+数组场景)
咱们用multipart/form-data格式提交,这是同时传文件和表单数据的标准方式,curl会自动帮你处理格式,API端也能正常识别数组:
客户端代码修改
直接把数组传给CURLOPT_POSTFIELDS,不用json_encode:
if(function_exists('curl_file_create')) { $cFile = curl_file_create($file_name_with_full_path); } else { $cFile = '@' . realpath($file_name_with_full_path); } // 直接构造数组,curl会自动处理成正确的表单数组格式 $post = array( 'destination' => ['00448923202'], 'file'=>$cFile ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_POST,1); // 直接传数组,curl自动生成multipart/form-data请求 curl_setopt($ch, CURLOPT_POSTFIELDS, $post); $result=curl_exec ($ch); curl_close($ch); // 注意先关闭curl再return,避免资源泄漏 return $result;
小提示:如果有多个目的地,直接在
destination数组里加元素就行,比如['00448923202', '00441234567'],curl会自动转成destination[]=xxx&destination[]=yyy的表单字段。
API端代码无需修改
原来的校验逻辑完全能用:
$destination = $request->post('destination'); if (!is_array($destination)) { return response()->json([ 'status' => 'error', 'message' => 'Make sure you are passing the destination field as an array' ]); }
补充:如果不需要传文件,只想用JSON格式提交
要是以后你不用传文件,只想发JSON数据,记得加请求头告诉API:
$post = array( 'destination' => ['00448923202'] ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_POST,1); // 必须加这个请求头,告诉API要解析JSON curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post)); $result=curl_exec ($ch); curl_close($ch); return $result;
这时候API端要改成从请求体解析JSON:
// 读取整个请求体并解析成数组 $input = json_decode(file_get_contents('php://input'), true); $destination = $input['destination'] ?? []; if (!is_array($destination)) { return response()->json([ 'status' => 'error', 'message' => 'Make sure you are passing the destination field as an array' ]); }
内容的提问来源于stack exchange,提问作者CodeNewbie
相关产品推荐
相关产品推荐

