How to Upload and Parse a CSV File in PHP

How to upload and parse a CSV file in php

Although you could easily find a tutorial how to handle file uploads with php, and there are functions (manual) to handle CSVs, I will post some code because just a few days ago I worked on a project, including a bit of code you could use...

HTML:

<table width="600">
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data">

<tr>
<td width="20%">Select file</td>
<td width="80%"><input type="file" name="file" id="file" /></td>
</tr>

<tr>
<td>Submit</td>
<td><input type="submit" name="submit" /></td>
</tr>

</form>
</table>

PHP:

if ( isset($_POST["submit"]) ) {

if ( isset($_FILES["file"])) {

//if there was an error uploading the file
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";

}
else {
//Print file details
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

//if file already exists
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
}
else {
//Store file in directory "upload" with the name of "uploaded_file.txt"
$storagename = "uploaded_file.txt";
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $storagename);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"] . "<br />";
}
}
} else {
echo "No file selected <br />";
}
}

I know there must be an easier way to do this, but I read the CSV file and store the single cells of every record in an two dimensional array.

if ( isset($storagename) && $file = fopen( "upload/" . $storagename , r ) ) {

echo "File opened.<br />";

$firstline = fgets ($file, 4096 );
//Gets the number of fields, in CSV-files the names of the fields are mostly given in the first line
$num = strlen($firstline) - strlen(str_replace(";", "", $firstline));

//save the different fields of the firstline in an array called fields
$fields = array();
$fields = explode( ";", $firstline, ($num+1) );

$line = array();
$i = 0;

//CSV: one line is one record and the cells/fields are seperated by ";"
//so $dsatz is an two dimensional array saving the records like this: $dsatz[number of record][number of cell]
while ( $line[$i] = fgets ($file, 4096) ) {

$dsatz[$i] = array();
$dsatz[$i] = explode( ";", $line[$i], ($num+1) );

$i++;
}

echo "<table>";
echo "<tr>";
for ( $k = 0; $k != ($num+1); $k++ ) {
echo "<td>" . $fields[$k] . "</td>";
}
echo "</tr>";

foreach ($dsatz as $key => $number) {
//new table row for every record
echo "<tr>";
foreach ($number as $k => $content) {
//new table cell for every field of the record
echo "<td>" . $content . "</td>";
}
}

echo "</table>";
}

So I hope this will help, it is just a small snippet of code and I have not tested it, because I used it slightly different. The comments should explain everything.

Uploading CSV using PHP

// check this url I hope it's useful ...

https://stackoverflow.com/questions/5593473/how-to-upload-and-parse-a-csv-file-in-php

OR

https://www.codexworld.com/import-csv-file-data-into-mysql-database-php/

Upload CSV into database using php

Here is the basic code which you need to do your task,

$file = fopen($_FILES['csvUpload']['tmp_name'], "r");
$i = 0;
while (!feof($file)) {
$value = (fgetcsv($file, 0, ';'));
if ($i > 0) {
if ($value[0] != '') {
$inserts[] = "(" . $value[0] . ","
. $value["1"] . ","
. $value["2"] . ","
. $value["3"] . ","
. $value["4"] . ","
. $value["5"] . ","
. $value["6"] . ")";
}
} elseif ($i == 0) {
$fields = $value;
}
$i++;
}

mysql_query("INSERT INTO `MyTable` (`" . $fields[0] . "`,`" . $fields[1] . "`,`" . $fields[2] . "`,`" . $fields[3] . "`,`" . $fields[4] . "`,`" . $fields[5] . "`) VALUES " . implode(",", $inserts));

fclose($file);

You have to implement validation, check file type and size limit. Then insert your data to the table. I have use MySQL bulk insert to handle large amount of data. Hope this helps!

EDIT 1:

Please replace your code with this code and see if it is working correctly.

<?php
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_WARNING);

mysql_connect('localhost', 'root', '');
mysql_select_db("proyecto") or die(mysql_error());

if (isset($_FILES['csvUpload'])) {
$errors = array();
$allowed_ext = array('.csv');

$file_name = $_FILES['csvUpload']['name'];
$file_ext = strtolower(end(explode('.', $file_name)));
$file_size = $_FILES['csvUpload']['size'];
$file_tmp = $_FILES['csvUpload']['tmp_name'];

if (in_array($allowed_ext) === false) {
$errors[] = 'La extensión del archivo no es valida.';
}
if ($file_size > 10485760) {
$errors[] = 'El archivo sobrepasa el limite de 10MB';
}
if (empty($errors)) {

$handle = fopen($file_tmp, "r");
while (($fileop = fgetcsv($handle, ";") && fgetcsv($handle, ",")) !== false) {
$cedula = mysql_real_escape_string($fileop[0]);
$nombre = mysql_real_escape_string($fileop[2]);
$apellido1 = mysql_real_escape_string($fileop[3]);
$apellido2 = mysql_real_escape_string($fileop[4]);
$correo = mysql_real_escape_string($fileop[5]);
$idRol = mysql_real_escape_string($fileop[6]);
$estado = mysql_real_escape_string($fileop[9]);

$sq1 = mysql_query("INSERT INTO `usuarios` (cedula,nombre,apellido1,apellido2,correo,idRol,estado) VALUES ('$cedula','$nombre','$apellido1','$apellido2','$correo','$idRol','$estado')");
}
fclose($handle);
if ($sq1) {
echo '¡Los usuarios han sido agregados exitosamente!';
}
}
}
?>

<form enctype="multipart/form-data" method="post" id="uploadForm">
<input name="csvUpload" id="upload" type="file" accept=".csv" class="left" />
<input type="submit" value="¡Cargar!" />
</form>

How to parse a CSV file using PHP

Just use the function for parsing a CSV file

http://php.net/manual/en/function.fgetcsv.php

$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}

Upload CSV file and check if value is empy to set it = 0 php

I'll update your code for add this section :

                if( count($column) < 13 ){

$tmpI = count($column);

while( $tmpI < 14 ){

$column[$tmpI] = 0;
$tmpI++;
}
}

The code check if you have 13 elements in your array, if not create the missing key with the value 0.

    $msg = 0;
if (isset($_POST['import'])) {
$fileName = $_FILES["file"]["tmp_name"];
if ($_FILES["file"]["size"] > 0) {
$file = fopen($fileName, "r");
$i = 0;
while (($column = fgetcsv($file)) !== FALSE) {
if ($i > 0) {
if (!empty($column[0])){

if( count($column) < 13 ){

$tmpI = count($column);

while( $tmpI < 14 ){

$column[$tmpI] = 0;
$tmpI++;
}
}

//$insertdate = date("Y-m-d", strtotime(str_replace('/', '-', $column[3])));
$sql = "INSERT into tab1 (country,jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dece)
values ('" . $column[0] . "','" . $column[1] . "','" . $column[2] . "','" . $column[3] . "','" . $column[4] . "','" . $column[5] . "','" . $column[6] . "','" . $column[7] . "','" . $column[8] . "','" . $column[9] . "','" . $column[10] . "','" . $column[11] . "','" . $column[12] . "')";
$result = mysqli_query($conn, $sql);
if (isset($result)) {
$msg++;
}
}
}
$i++;
}
}
}

How to upload a CSV file and save it into an multidimensional array?

Create a simple file upload form in html which will upload a file to your php script yourscript.php via post when the submit button is pressed. Make sure to name your file type input something nice because you will need to reference that name in php

<form action="yourscript.php" method="post" enctype="multipart/form-data">
<input type="file" name="upload_file" />
<input type="submit" />
</form>

PHP yourscript.php

<?php
$csv_array = Array();
$file = fopen($_FILES['upload_file']['tmp_name'], 'r');
if($file){
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
array_push($csv_array,$line);
}
fclose($file);
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>var your_array = <?php echo json_encode($csv_array); ?></script>
</head>
<body>

</body>
</html>

from How to create an array from a CSV file using PHP and the fgetcsv function

Things get a little trickier when you start using ajax to handle file uploads so i suggest you learn how ajax works before attempting to use ajax to do file uploading



Related Topics



Leave a reply



Submit