PHP Tutorials: How to read a CSV file?

While working as a developer you might have heard this term “CSV file” a lot of times. But what actually a CSV file is?

A CSV is a comma-separated values file, which allows data to be saved in a tabular format. CSVs look like a garden-variety spreadsheet but with a . CSV extension. CSV files can be used with most any spreadsheet program, such as Microsoft Excel or Google Spreadsheets.

Read a CSV file in PHP

The code to read a CSV file is very simple. Below is the code:

<?php

$file = fopen("lang.csv","r");

$data = [];
while(! feof($file)){
	
	$data[] = fgetcsv($file);
	
}
echo "<pre>";
print_r($data);
echo "</pre>";
fclose($file);
?>

What the code is doing?

  • fopen(): This function open the file and assign the resource to the $file variable. The function takes 2 parameters. 1st is the the file name. 2nd is the mode the file has to open in the buffer. The point to notice here is the file name should be PATH + FILENAME. So that the function can find the file.
  • feof(): This function checks if the end of the file has been reached. Otherwise the while loop will never exit and it will be an infinite loop.
  • fgetcsv(): This function reads the current row of the CSV file.
  • fclose(): This function releases the resource occupied by the fopen function. Don’t forgot to close a file otherwise it will keep the resource occupied and the server may run out of memory.

Comment below if you have any question.

Leave a Reply

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