【问题标题】:use arrays to post to cURL with same input name使用数组以相同的输入名称发布到 cURL
【发布时间】:2015-03-26 05:35:26
【问题描述】:

我想提交数组到 cURL

<form action="post.php" method="post">
    <input name="comment[]" value="oh"/><br>
    <input name="comment[]" value="wow"/><br>
    <input name="comment[]" value="like"/><br>
    <input type="submit" />
</form>

我希望结果像这样发送到 curl:

curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_POST, 1);
    curl_setopt ($ch, CURLOPT_POSTFIELDS, "0=oh&1=wow&2=like");
    $hasil = curl_exec ($ch);
    curl_close ($ch);

post.php 文件:

$inputs = $_POST['comment']; print_r($inputs);

结果:

Array
(
    [0] => oh
    [1] => wow
    [2] => like
)

如何将结果发送到 cURL?

【问题讨论】:

标签: php html arrays curl input


【解决方案1】:

根据发布的值构建查询字符串:

$query_string = http_build_query($_POST['comment']);

并通过 curl 提交:

curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $query_string);
$hasil = curl_exec ($ch);
curl_close ($ch);

【讨论】:

    【解决方案2】:

    有一个函数http_build_query() 可以为你完成这项工作。

    例如:

    $querystring = http_build_query($inputs);
    
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_POST, 1);
    curl_setopt ($ch, CURLOPT_POSTFIELDS, $querystring);
    $hasil = curl_exec ($ch);
    curl_close ($ch);
    

    【讨论】:

      【解决方案3】:

      你的实际问题是

      如何使用 cURL 发布数据数组?

      这个问题已经回答here

      您将使用函数 http_build_query() 从您的索引 comment 数组构建一个 URL 编码字符串。

      这段代码应该可以解决问题。

      curl_setopt ($ch, CURLOPT_POSTFIELDS, http_build_query($inputs))

      您可能需要将 Content-Type 标头设置为 multipart/form-data,如curl_setopt documentation 中所述。

      【讨论】:

        猜你喜欢
        • 2014-05-06
        • 1970-01-01
        • 1970-01-01
        • 2017-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-14
        • 1970-01-01
        相关资源
        最近更新 更多