How to read csv file using PHP

This article is about how to read the CSV files using PHP. I have implemented simple and easy way of handling the CSV file in PHP. I have used PHP inbuilt function called fgetcsv to open and read CSV files. You can use this method to insert the CSV data to MYSQL database.

PHP read CSV files

You can view demo and download how to read CSV files using PHP:

Live Demo Download

PHP read csv file:

Now lets see how the code look like. As i mentioned earlier we have used php function called fgetcsv(). This function will gets line from file pointer to parse for CSV fields and return an array.

//FUnction to read CSV
function readCSV($csvFile){
    //Open the file in read mode
	$file_handle = fopen($csvFile, 'r');
    //Go through a loop
	while (!feof($file_handle) ) {
        // get data using fgetcsv and push to an array
		$line_of_text[] = fgetcsv($file_handle, 1024);
    //Close the file after reading
    //return the array of data
	return $line_of_text;

// Set path to CSV file
$csvFile = 'invoices.csv';

//call the csv reading function
$csv = readCSV($csvFile);

// Output the aarray in to brower
//You can insert to db from here

If you want to insert this data to database, go through a loop like below,

//Loop to insert to DB
for($i=1; $i<$arraySize; $i++)
  //Your sql statement goes here
  echo $csv[$i][0].'<br />';
  echo $csv[$i][1].'<br />';

Above function will return you a set of data in php array format. You can go through a loop and insert to database also.

Hope that this will help you. If you liked, don’t forget to share this article with your friends. Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>