1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
|
<!-- form to download a csv file from the hard disk -->
<form action="" method="post" enctype="multipart/form-data">
<label for="file2"><b>File CSV</b></label>
<input type="file" name="file2" id="file2"><br/>
<input type="submit" name="submitfile2" value="csv file download"><br/>
</form>
<?php
if (!defined('DIR_ROOT')) define('DIR_ROOT', dirname(__DIR__).DIRECTORY_SEPARATOR);
if (isset($_POST['submitfile2']))
{
//to put the file into an array ($data): each cell of the array contents a line of the csv file
if (!$_FILES['file2']["error"]) { //if not error
$upload_dir = 'csv';
$name=$_FILES['file2']['name'];
if ( false === $handle = fopen(DIR_ROOT.$upload_dir.DIRECTORY_SEPARATOR.$name, 'r') )
throw new Exception("impossible to open the file '$name'");
// one reads the header
$buffer = 4096;
if ( false === ($header = fgets($handle, $buffer)) )
throw new Exception("The file '$name' is empty");
// one tests different separators
$sep = ','; // by default
$separators = [',', ';'];
foreach ($separators as $separator) {
if ( strpos($header, $separator)> 0) {
$sep = $separator;
break;
}
}
function addDb($str)
{
return('"'.$str.'"');
}
while (false !== ($fields = fgetcsv($handle, $buffer, $sep)) ) {
$fields_convert=[];
foreach($fields AS $str_fields)
{
$str_fields=addDb($str_fields);
$fields_convert[]=$str_fields;
}
$line_csv=implode(",", $fields_convert);
file_put_contents('exemple.csv', $line_csv."\r\n", FILE_APPEND ); // serveur Windows , donc \r\n
}
} //end if not error
}
?> |
Partager