How to Parse a CSV File Using PHP

In this tutorial you will learn a simple way to parse CSV files using PHP and output the text of the fields you need. This tutorial is not going to go into what you can do with the data once you get it from the CSV as the possibilities are endless. We will simply show you how to get the data into an array in PHP.


First you can download our test.csv file here.

Now we are going to open the file for reading using the fopen() function in PHP. Will will specify the location of the file and also the mode in which we want to open it. In this case we are using the “R” mode which stands for read. Other possible uses of this function can be found on the manual page for fopen().

<?php

$handle = fopen("test.csv", "r");

?>

Next we are going to create a while loop. We will use this loop to parse each line of the CSV.

<?php
$handle = fopen("test.csv", "r");

while () {

	
}
?>

Next we are going to use the fgetcsv() function to “split” each line of our CSV file into an array called $data. When there are no lines left the condition will be false and will end the loop. In the fgetcsv() function we will pass the file handle, length (optional) and the separating character (which is a comma in this case.
test

<?php

$handle = fopen("test.csv", "r");

while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {

	
}
?>

*note: If you data fields are encapsulated using a character such as – (for ease of example) you can specify the enclosure filed like so: fgetcsv($handle, 5000, “,”,”-“). By default the enclosure character is a double quote, but the function will also handle no enclosure character.

Next all we have to do is echo the fields that we want to see. We will use the field number in the array to do this. I will echo the second value in the CSV.

<?php

$handle = fopen("test.csv", "r");
$row = 1;
while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
	echo $data[2];
	echo "</br>";
}
?>

Another note. If you do not know which value the field you are looking for will be in the array just print the array like this:

<?php

$handle = fopen("test.csv", "r");

while (($data = fgetcsv($handle, 5000, ",")) !== FALSE) {
	echo "<pre>";
	print_r($data);
	echo "<pre>";
}
?>

As you can see it is pretty simple to parse csv using this method.

Subscribe To Our Newsletter

Subscribe To Our Newsletter

Join the TeamTutorials mailing list and get the latest tips, tricks, and special discounts for members only.

Thanks! Please click the link in the email we just sent you to confirm.

Published by

Johnathan Ward

Johnathan Ward is an experienced developer and consultant that writes tutorials to help other developers. In his day job, he is an IBM Watson Explorer Consultant with several years of experience deploying and customizing Watson Explorer solutions. Follow me on twitter