使用 CURLOPT_POSTFIELDS 时进行数组 2 字符串转换


Array 2 string conversion while using CURLOPT_POSTFIELDS

我有以下代码:

// $postfields = array();
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);

我的$postfields变量是一个参数数组。我注意到有数组到字符串的转换。它有效。

我可以使用http_build_query()函数来取消通知,但是我使用@path_to_file来包含帖子文件。 和http_build_query()中断文件包含。

我想知道是否有更"适当"的方法可以做到这一点。无需生成通知。

$postfields数组本身的某些值是吗?这很可能是导致通知的原因。 curl_setops期望它的第三个参数是一个数组,其键和值是字符串,如 PHP 的函数手册页中所述,尽管它可能不是很清楚:

此参数可以作为 urlencoding 字符串传递,例如 'para1=val1&para2=val2&...'或作为数组,字段名称作为键,字段数据作为值。

在这句话中,关键点是 para1/2 和 val1

/2 是字符串,如果需要,您可以将它们作为数组提供,其中键是 para1 和 para2,值是 val1 和 val2。

有两种方法可以消除通知

第一种是使用 http_build_query() 并将您对@filepath的使用替换为 CURLFile 对象。不幸的是,这只有在您使用的是 PHP 5.5 或更高版本时才有可能。手册的页面有一个非常清晰和简单的使用示例。

如果使用 CURLFiles 不适合您,那么第二种方法是json_encode() $postfields数组的值,这些值本身就是数组。这并不优雅,它需要你解码另一端的 JSON。

如果要发送多维数组,j11e 的答案将不起作用

试试这个递归函数。

https://gist.github.com/yisraeldov/ec29d520062575c204be7ab71d3ecd2f

<?php
function build_post_fields( $data,$existingKeys='',&$returnArray=[]){
    if(($data instanceof CURLFile) or !(is_array($data) or is_object($data))){
        $returnArray[$existingKeys]=$data;
        return $returnArray;
    }
    else{
        foreach ($data as $key => $item) {
            build_post_fields($item,$existingKeys?$existingKeys."[$key]":$key,$returnArray);
        }
        return $returnArray;
    }
}

你可以像这样使用它。

curl_setopt($ch, CURLOPT_POSTFIELDS, build_post_fields($postfields));

使用 Laravel,对我有用的一件事是在请求标头中使用标签"内容类型:应用程序/json",并发送我的数据 json 编码如下:

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Accept: application/json'));
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

在接收请求中参数的函数中,我不需要使用 json 解码函数,我访问参数就像

$request->something

经过一个小时的研究,我在这里修复了我的代码:

$strVar = '';
if ($data) {
        $ea = build_post_fields($data);
        foreach($ea as $key=>$val) {
                $strVar.= "$key=$val&";
        }
}

/* eCurl */
$curl = curl_init($url);
/* Set Array data to POST */
curl_setopt( $curl, CURLOPT_POSTFIELDS, ($strVar) );

这是我从下面的@Yisrael Dov中获取的功能:


function build_post_fields( $data, $existingKeys='', $returnArray=[]){
    if(($data instanceof CURLFile) or !(is_array($data) or is_object($data))){
        $returnArray[$existingKeys]=$data;
        return $returnArray;
    }
    else{
        foreach ($data as $key => $item) {
            build_post_fields($item,$existingKeys?$existingKeys."[$key]":$key,$returnArray);
        }
        return $returnArray;
    }
}

那工作完美!您可以发布一个深度数组,例如:

$post_var = array(
'people' => array('Lam', 'Hien', 'Nhi'),
'age' => array(12, 22, 25)
);

日安!