【问题标题】:Unable to pass an ARRAY through CURL?无法通过 CURL 传递数组?
【发布时间】:2018-05-16 21:54:40
【问题描述】:
$items[] = array("sku"=>"data","name"=>"data","amount"=>0,"qty"=>"0","id"=>"data","price"=>0,"url"=>"data");

$post = array(
'data' => 'data',
            'items' => $items);

$ch = curl_init('urltopost');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
//curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0); 
curl_setopt($ch, CURLOPT_TIMEOUT, 3); //timeout in seconds
header('Content-Type: text/html');
echo curl_exec($ch);

// Check if any error occurred
if(curl_errno($ch))
{
     header('Location: error');
     die();
}

如果我将其发布到自己并执行var_dump($_POST["items"]);,我只会得到string(5) "Array" 作为输出。

我还尝试了一个不输出数据的 foreach 循环。

我是不是傻了,有什么明显的问题?

【问题讨论】:

  • var_dump($_POST) 我想你会看到这个问题
  • 这给了我我想要的所有数据,你能向我指出问题吗?
  • $items[] .. 创建一个新维度,因此它最终为 $items[0] .. 你可以只使用 $items=array()ideone.com/FUJwGd
  • @smith 我把它改成了 $items = array();可悲的是它没有任何区别
  • 设置curl_setopt($ch, CURLOPT_POSTFIELDS, $items); 应该也可以。来自文档Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.。在您的情况下,问题似乎是您正在用另一个数组包装 $items。

标签: php arrays curl arraylist php-curl


【解决方案1】:

你可以试试这个

$post = [];
foreach($items as $index=>$item){
    $new_key = "item[$index]";
    foreach($item as $k=>$v){
        $post[$new_key.'['. $k .']'] = $v;
    }

}
$post['data'] = 'data';

帖子数组格式为array('key'=>string, ....),它不允许数组。如果你想要发布数组,键格式是'key[index1][index2] ...'。在服务器中,您将收到 $_POST['key'] 作为数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-12
    • 1970-01-01
    • 1970-01-01
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 2015-04-02
    • 1970-01-01
    相关资源
    最近更新 更多