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.

  • I’m trying to parse a CSV file with ruby and have not found any good tutorials online. Also, I’ve looked at the API documentation and its still difficult/tedious to follow.

  • serengeti

    If I use your tutorial, special characters in the csv like ‘, %, etc are not read correctly and when displayed look like ’

  • Thanks for the great tutorial. I still have a way to go before I get my CSV to WordPress Post plugin properly working but this is a much better solution than the one I currently have in place.

  • RandiR

    Very good tutorial. I use CSVs a lot for stock market data. If you need to parse stock market data, there is a good sample script posted at http://www.biterscripting.com/SS_CSV.html . There are also some good tutorials on scripting at that site.

    Randi

  • @serengeti
    That’s not a problem with the tutorial. Character encoding is a whole different topic. You could try to use utf8_decode(). http://us3.php.net/manual/en/function.utf8-decode.php

  • Many Thanks for the amazing tutorial. I still have a way to go before I get my CSV to WordPress Post plugin properly working but this is a much better solution than the one I currently have in place.

  • it is really nice post with a good info.keep it up……

  • i am a beginner of php, i have tried to find the solution for many times. but the official manual is hard to follow. i have test your method, that is ok….but i don’t understand very well, so hoping your next post…

  • Many Thanks for this great tutorial.

  • im writing a script to download a file using php and curl. but downloading is just too slow, i want to open multiple connections to the server and download the file (hence accelerate the download). how can i do this ?

  • Once you create this simple address book add sessions, so that once you are idle for about 5 min you have to log in again to view data. Make it more authentic by adding validation etc.

  • I have a colum in a MySQL database that uses datatype TIMESTAMP to save the date and time that a new row is inserted. This displays like 2008-09-21 09:31:25 when retrieved and echoed using PHP.

  • Thanks for tutorial, this is very helpful to us.

  • By the way i love mysql even due im creating a system for land base.

  • I’ll give an example for a table with these fields: name, lastname, age, email. the name of the csv file is fixed, but can make a form to let the user pick the file and folder. I use the function convertString to put quotes and replace the quotes by double quotes in the text fields.

  • The text fields are enclosed between quotes. For example if field2 is a text field you can use: field1;”field2″;field3;… The in-string quotes of the field two are converted to double quotes.

  • ll give an example for a table with these fields: name, lastname, age, email. the name of the csv file is fixed, but can make a form to let the user pick the file and folder.

  • Decrypting an encrypted file with PHP and GnuPG can be a bit more complex than encrypting, since you are required to provide a GnuPG passphrase.

  • Also you could go with IonCube which is on a large percentage of servers now.

  • Nice tutorial, it was help me a lot in developing my own script 🙂

  • Vlad

    i’m having a little trouble getting things to echo. i simplified the script to this:

    and yet nothing gets echo’d. I’ve tried to used “print” instead of echo as well. what i expect to happen is that the contents of test.csv would print out. thanks in advance

    • Vlad

  • Many Thanks for scripts.

  • aaiiii… I’m running less than 5.3, soooo… I’m in need of doing it manually. Anyone having a super algorithm for the job ?

  • Reynante Santiago

    Nice. 🙂

  • Rik

    Hi!
    I tried to put this code in an html page

    and it does not work

    only when the code is in a PHP file extension

    • Brent

      Thats because this is not HTML. This is PHP and the server doesn’t know to look for and execute php code unless the file extension is .php

  • Thanks i was finding this tutorial for my new site USA health care blog i need to read customer csv data . Thanks for sharing

  • Pingback: PHP fgetcsv Tutorial | KC-TUTOR()

  • Thanks for the tip, using this in my next project 🙂

  • Spaapk

     Thank you so much! it’s a lot simpler that I thought 🙂

  • well, I have used this, http://code.google.com/p/parsecsv-for-php/ its running well.. just try it

  • “You may have issue with memory if you try to open large files using
    fopen. in that case you will want to read the file line-by-line, but
    that is another tutorial.” no you wont. because you will always just have one line cached in the $data array. you can run fgetcsv on terabytes of data without any issues.

    • Hmmm. I think you are right. I wrote this a very long time ago. fopen() just creates a pointer to the file. Maybe I was thinking of fread() storing the entire contents to memory. fgets and fgetscsv should be line-by-line.

  • another cool thing when parsing through a file would be an indicator of some sort. like this for example:

    while (($data = fgetcsv($handle, 5000, “,”)) !== FALSE) {
    $i++;
    if($i%1000==0) echo “$i lines parsedn”;

    }

  • Thank you so much! it’s a lot simpler that I thought 🙂

  • I see you share interesting things here, you can earn some extra money, your blog has
    big potential, for the monetizing method, just type in google – K2 advices how to
    monetize a website