Purpose of writing this post to show an example how to upload and read csv file using php code. CSV is comma separated values which commonly used to store data like Excel.
PHP Read CSV File
PHP has inbuilt function fgetcsv() which parse a line from an open CSV file.
Syntax: fgetcsv (file,length,separator,enclosure)
Here file and length are required parameter and other two are optional. length specifies the maximum length of line. separator parameter use as file separator like (,).
Upload CSV file in PHP:
To upload csv file use input html tag as type “file” value. use below html code to achieve this:
<form enctype='multipart/form-data' action='' method='post'>
<label>Upload Product CSV file Here</label>
<input size='50' type='file' name='filename'>
<input type='submit' name='submit' value='Upload Products'>
PHP Read CSV File Code:
Let assume we can upload and read csv file on same PHP file page. After submit upload csv file get the form post and use fopen and fgetscv function to read csv file. Use below php parse csv file code:
$handle = fopen($_FILES['filename']['tmp_name'], "r");
$headers = fgetcsv($handle, 1000, ",");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
In this read csv file code, each cell value will get in $data array variable. You can parse this array to get separated value. Thats it, very easy to implement this functionality.