06.18.2009

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. 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.

Related Posts

Comments

  1. Swiss Cheese on June 22, 2009 at 2:15 pm

    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.

    [Reply]

  2. serengeti on July 10, 2009 at 1:29 am

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

    [Reply]

  3. Buy PSP Go on July 19, 2009 at 2:00 pm

    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.

    [Reply]

  4. RandiR on July 27, 2009 at 1:25 pm

    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

    [Reply]

  5. John Ward on August 17, 2009 at 12:58 pm

    @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

    [Reply]

  6. generic on August 26, 2009 at 7:36 pm

    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.

    [Reply]

  7. football on September 4, 2009 at 5:11 am

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

    [Reply]

  8. links of london on September 5, 2009 at 9:47 pm

    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…

    [Reply]

  9. generic on September 6, 2009 at 12:40 pm

    Many Thanks for this great tutorial.

    [Reply]

  10. Home made hand jobs on November 3, 2009 at 5:48 am

    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 ?

    [Reply]

  11. football on November 28, 2009 at 12:12 am

    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.

    [Reply]

  12. football on November 28, 2009 at 12:13 am

    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.

    [Reply]

  13. Cetvn on January 24, 2010 at 1:47 am

    Thanks for tutorial, this is very helpful to us.

    [Reply]

  14. Cetvn on January 24, 2010 at 1:48 am

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

    [Reply]

  15. motocross clothing on February 1, 2010 at 5:31 am

    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.

    [Reply]

  16. motocross clothing on February 8, 2010 at 4:49 am

    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.

    [Reply]

  17. web design brisbane on February 12, 2010 at 3:12 am

    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.

    [Reply]

  18. motocross clothing on February 13, 2010 at 12:56 am

    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.

    [Reply]

  19. John Ward on March 5, 2010 at 8:29 pm

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

    [Reply]