如何使用curl在数组中发布数组

时间:2016-04-22 13:10:03

标签: php arrays post curl

我正在尝试使用带有API的curl并将值发布到它。 我在一个关联数组中发布参数,其中除了一个值(另一个数组)之外,所有值都是字符串,整数或布尔值。 (所以在另一个数组中有一个数组。)

问题是:第二个阵列没有正确发送,我无法让它工作。 最初的问题是'数组到字符串转换'所以我开始在params数组周围使用http_build_query(),它停止了这个问题,但它不起作用。

我知道这可能是我的代码而不是外部API的问题,因为其他开发人员正在使用其他语言的API。

PHP代码:

    $url = '{url}';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    $headers = array("X-Auth-Token: $json_token");
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $params = array(
            'name' => 'sample_name',
            'types' => array('web'),
            'limit' => 2,
            'auto' => true
    );
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
    $out = curl_exec($ch);
    curl_close($ch);

3 个答案:

答案 0 :(得分:1)

form submission formats都不支持嵌套(多维)数组。换句话说,你不能在POST请求中发送嵌套数组作为表单编码数据(CURL默认使用application/x-www-form-urlencoded格式)。您很可能误解了API规范。也许API接受其他格式的数据,例如,JSON允许任何级别的嵌套。

答案 1 :(得分:0)

尝试使用serialize

// Data to post 
$postData = array( 
  'name' = 'foo', 
  'data' = serialize(array(1,2,3,4)), 
  'value' = 'bar' 
); 

// Will not error 
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData); 
?>

点击此处:http://nl1.php.net/manual/en/function.curl-setopt.php#99108

答案 2 :(得分:0)

试试这个......

$url = '{url}';
$params = array(
        'name' => 'sample_name',
        'types' => array('web'),
        'limit' => 2,
        'auto' => true
);
$data_string = json_encode($params);                                                                                   

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); 
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);  
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,0);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data_string))                                                                       
);                                                                                                                   

$out = curl_exec($ch);
curl_close($ch);
相关问题