如何在 cURL POST 请求中使用数组 [英] How do I use arrays in cURL POST requests

查看:29
本文介绍了如何在 cURL POST 请求中使用数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何让这段代码支持数组?目前 images 数组似乎只发送第一个值.

I am wondering how do I make this code support arrays? At the moment the images array only seems to send the first value.

这是我的代码:

<?php
//extract data from the post
extract($_POST);

//set POST variables
$url = 'http://api.example.com/api';
$fields = array(
            'username' => "annonymous",
            'api_key' => urlencode("1234"),
            'images[]' => urlencode(base64_encode('image1')),
            'images[]' => urlencode(base64_encode('image2'))
        );

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);
echo $result;

//close connection
curl_close($ch);
?>

这是在 api 接收到的内容

and this is what is received at the api

VAR: username = annonymous
VAR: api_key = 1234
VAR: images = Array
array(3) { 
         ["username"]=> string(10) "annonymous" 
         ["api_key"]=> string(4) "1234" 
         ["images"]=> array(1) { // this should contain 2 strings :( what is happening?
                               [0]=> string(8) "aW1hZ2Uy" 
                               } 
         }

images[] 中的第二个值发生了什么变化?

What is happening to the second value in images[]?

推荐答案

您只是错误地创建了数组.你可以使用 http_build_query:

You are just creating your array incorrectly. You could use http_build_query:

$fields = array(
            'username' => "annonymous",
            'api_key' => urlencode("1234"),
            'images' => array(
                 urlencode(base64_encode('image1')),
                 urlencode(base64_encode('image2'))
            )
        );
$fields_string = http_build_query($fields);

因此,您可以使用的整个代码是:

So, the entire code that you could use would be:

<?php
//extract data from the post
extract($_POST);

//set POST variables
$url = 'http://api.example.com/api';
$fields = array(
            'username' => "annonymous",
            'api_key' => urlencode("1234"),
            'images' => array(
                 urlencode(base64_encode('image1')),
                 urlencode(base64_encode('image2'))
            )
        );

//url-ify the data for the POST
$fields_string = http_build_query($fields);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);
echo $result;

//close connection
curl_close($ch);
?>

这篇关于如何在 cURL POST 请求中使用数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆