How to programatically HTTP POST a CSV file directly from an array in PHP?
Intreesting question. The only thing I can think of is that you echo the "csv data" with headers of a post and that it's a csv file. That should not create a file on the server afaik. Not sure fully how to approach it, but if you run set apache headers or whichever server system you're using. Give it a shot and let me know if it works.
I managed to capture the csv data in to a variable using fputcsv to php://output with output buffering. Since the service only allows multipart format for the submission, you need to construct the payload like this.
<?php//Construct your csv data$celldata = array( array( "heading1", "heading2", "heading3", ), array( 1, 2, 3, ), array( 4, 5, 6, ));//Output to php://outputob_start();$outstream = fopen("php://output", 'w');foreach($celldata as $cell) { fputcsv($outstream, $cell);} fclose($outstream) or die();$csv_data = ob_get_clean();$url = 'http://opencellid.org/measure/uploadCsv';// Taken from http://stackoverflow.com/questions/3085990/post-a-file-string-using-curl-in-php// form field separator$delimiter = '-------------' . uniqid();// file upload fields: name => array(type=>'mime/type',content=>'raw data')$fileFields = array( 'datafile' => array( 'type' => 'text/plain', 'content' => $csv_data, ),);// all other fields (not file upload): name => value$postFields = array( 'key' => 'opencellidapikey', //Put your api key here);$data = '';// populate normal fields first (simpler)foreach ($postFields as $name => $content) { $data .= "--" . $delimiter . "\r\n"; $data .= 'Content-Disposition: form-data; name="' . $name . '"'; $data .= "\r\n\r\n"; $data .= $content; $data .= "\r\n";}// populate file fieldsforeach ($fileFields as $name => $file) { $data .= "--" . $delimiter . "\r\n"; $data .= 'Content-Disposition: form-data; name="' . $name . '";' . ' filename="' . $name . '"' . "\r\n"; $data .= 'Content-Type: ' . $file['type'] . "\r\n"; $data .= "\r\n"; $data .= $file['content'] . "\r\n";}$data .= "--" . $delimiter . "--\r\n";$handle = curl_init($url);curl_setopt($handle, CURLOPT_POST, true);curl_setopt($handle, CURLOPT_HTTPHEADER , array( 'Content-Type: multipart/form-data; boundary=' . $delimiter, 'Content-Length: ' . strlen($data))); curl_setopt($handle, CURLOPT_POSTFIELDS, $data);curl_setopt($handle, CURLOPT_RETURNTRANSFER,1);$result = curl_exec($handle);var_dump($result);
I get API key error, but it should work.