Read CSV file with PHP

Reading the content of a CSV file can be done with PHP easily; thanks to PHP built-in function fgetcsv. Below is the sample code to read CSV file (comma separated). The content of the CSV file is shown below.

Sales per State,CA,AZ,TX,NY
Jan,323,324,5435,5334
Feb,423,6646,54,34
Mar,422,645,545,23
Apr,565,477,443,232
May,634,6454,54354,2323
Jun,645,656,433,4242
July,333,7565,3433,53535

Below is the PHP code to read a CSV file.

<?php
 
$file = 'TestData1.csv'; 
 
//The delimiter that is used in csv file.
$delimiter = ',';
 
//Open the TestData1.csv file for reading.
$handle = fopen($file, "r");
 
if($handle)
{
	//Read each line and print the line out.
	while (($line_array = fgetcsv($handle, 4000, $delimiter)) !== false) {
 
		//Do something to each line.
		echo "<pre>";
		print_r($line_array);
		echo "</pre>";
	}
	fclose($handle);
}
 
?>

Once the CSV file is opened using fopen, we can read each line in the input file. The function fgetcsv takes one required parameter and 2 optional parameters. The first parameter is the file pointer to a file successfully opened by fopen function. The second parameter is the number of characters that fgetcsv should read from a line in the CSV file. In this example, I set this parameter to 4000 characters. If this second parameter is set to zero, then fgetcsv will read the entire line no matter how long the line is. However, setting this parameter to zero might take PHP more time to read a line if your CSV file is long and complex. The third parameter is the delimiter that is used in the CSV file. By default, the third parameter is set to a comma.

This entry was posted in PHP. Bookmark the permalink.

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=""> <strike> <strong>