Import CSV file data to show in HTML with PHP

This simple script shows you how to import data of a CSV file and for show purpose we will us an HTML table.  First we will create a form so that we can browse CSV file. Use the below code:

<table cellpadding=”0″ cellspacing=”0″ border=”1″ style=”width:600px; min-height:30px; margin:0 auto;”>
<tr>
<td colspan=”3″ align=”center”>
<form action=”<?php echo $_SERVER[‘PHP_SELF’];?>” method=”post” enctype=”multipart/form-data” name=”import”>
<label for=”csv_file”>Browse CSV file:</label>
<input name=”csv_file” id=”csv_file” type=”file”>
<input name=”csvsubmit” id=”csvsubmit” value=”Import” type=”submit”>
</form>
</td>
</tr>
</table>

Now it’s time to add PHP code to process the CSV data and show in HTML as table format. Use the below code:

    <?php
if(isset($_POST[‘csvsubmit’])) {//CHECK THE FORM SUBMITTED OR NOT
if($_FILES[‘csv_file’][‘tmp_name’]) {//CHECK IF THE CSV FILE UPLOADED
$handle = fopen($_FILES[‘csv_file’][‘tmp_name’], “r”);
while (($data = fgetcsv($handle, 1000, “,”)) !== FALSE) {
$num = count($data);
echo “<tr>”;
for ($c=0; $c < $num; $c++) {
?>
<td>
<?php echo $data[$c]; ?>
</td>
<?php
}
echo “</tr>”;
}
fclose($handle);
} else {//IF THE FORM SUBMITTED AND CSV FILE NOT FOUND THEN BELOW RESULT
?>
<tr>
<td colspan=”3″ align=”center”>
No CSV File Found
</td>
</tr>
<?php
}
}
?>

isset($_POST[‘csvsubmit’]) :
Check if the user click on the Import button that’s means the form submitted or not.

$_FILES[‘csv_file’][‘tmp_name’] :
Check whether the CSV file uploaded and we found the CSV file tmp name.

fopen() :
fopen () function is used to read the CSV file and store into the $handle variable. We provide 2nd parameter “r” as read permission.

fgetcsv() :
In the while loop we provide 3 parameter to fgetcsv()  function.

  • First parameter is required; specifies the file
  • Second parameter is optional; specifies the maximum length of a line. Must be greater than the longest line (in characters) in the CSV file.
  • Third parameter is also optional; it is a character that specifies the field separator. Default is comma ( , ).

Now it’s time to check the code in your server. Output may be the below screen shot.

To download the source code pls click here.

Author Info

Shah Alom

Hi, This is Mohammad Shah Alom, My passion is Programming & Web Development. I am Founder of Micro Solutions Bangladesh. My Facebook profile shahalom1983 & Twitter Profile shahalom_83