2016-04-22 29 views
0

我正在嘗試使用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); 

回答

1

form submission formats均不支持嵌套(多維)數組。換句話說,你不能在POST請求中發送嵌套數組作爲表單編碼數據(CURL默認使用application/x-www-form-urlencoded格式)。很可能你誤解了API規範。也許API接受其他格式的數據,例如JSON,它允許任何級別的嵌套。

+0

是的!我改變了內容類型並將數組編碼爲json,並且它工作正常!謝謝! – user5331188

+0

@ user5331188如果它解決了您的問題,您也可以upvote這個答案 – hindmost

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); 
+0

剛剛嘗試過,沒有任何改變。 – user5331188

+0

@ user5331188我編輯了答案試試這個.. –