在 cURL POST 請求中支援數組
在此查詢中,使用者尋求有關如何在 cURL POST 請求中使用數組的指導。在提供的程式碼中使用陣列時,僅提交第一個值。透過研究提交的程式碼,發現了以下問題:
<code class="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);</code>
陣列結構不正確:
主要問題在於以下位置的陣列結構不正確:
<code class="php">'images[]' => urlencode(base64_encode('image1')), 'images[]' => urlencode(base64_encode('image2'))</code>
這種方法不會在PHP 中建立陣列;相反,每個鍵「images[]」都會覆寫前一個。
正確的數組結構(使用http_build_query):
要正確建構數組,請考慮使用http_build_query 函數:
<code class="php">$fields = array( 'username' => "annonymous", 'api_key' => urlencode("1234"), 'images' => array( urlencode(base64_encode('image1')), urlencode(base64_encode('image2')) ) ); $fields_string = http_build_query($fields);</code>
修訂後的程式碼:
合併這些調整,修改後的程式碼將如下所示:<code class="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);</code>
以上是如何在 cURL POST 請求中正確提交陣列?的詳細內容。更多資訊請關注PHP中文網其他相關文章!