Purpose of writing this post to show an example of how to upload and read csv file using PHP code. CSV is a comma-separated value which commonly used to store data like Excel.
Read CSV File in PHP
PHP has an 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 the other two are optional. The 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:
1 2 3 4 5 6 7 8 9 |
<form enctype='multipart/form-data' action='' method='post'> <label>Upload Product CSV file Here</label> <input size='50' type='file' name='filename'> </br> <input type='submit' name='submit' value='Upload Products'> </form> |
PHP Read CSV File Code:
Let assume we can upload and read CSV file on the same PHP file page. After submitting the upload CSV file get the form post and use fopen and fgetscv function to read CSV file. Use below PHP parse CSV file code:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
if (isset($_POST['submit'])) { $handle = fopen($_FILES['filename']['tmp_name'], "r"); $headers = fgetcsv($handle, 1000, ","); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $data[0]; $data[1]; } fclose($handle); } |
In this read csv file code, each cell value will get in $data array variable. You can parse this array to get separated value. That’s it, very easy to implement this functionality.
What is the “1000” for?
Hi, this is used for maximum length of a line.