Programming Tutorials

Reading .CSV file in PHP

By: David Sklar in PHP Tutorials on 2008-12-01  

You have data in comma-separated values (CSV) format, for example a file exported from Excel or a database, and you want to extract the records and fields into a format you can manipulate in PHP.

If the CSV data is in a file (or available via a URL), open the file with fopen()and read in the data with fgetcsv(). This prints out the data in an HTML table:

$fp = fopen('sample2.csv','r') or die("can't open file");
print "<table>\n";
while($csv_line = fgetcsv($fp,1024)) {
    print '<tr>';
    for ($i = 0, $j = count($csv_line); $i < $j; $i++) {
        print '<td>'.$csv_line[$i].'</td>';
    }
    print "</tr>\n";
}
print '</table>\n';
fclose($fp) or die("can't close file");

The second argument to fgetcsv() must be longer than the maximum length of a line in your CSV file. (Don't forget to count the end-of-line whitespace.) If you read in CSV lines longer than 1K, change the 1024 used in this recipe to something that accommodates your line length.

You can pass fgetcsv() an optional third argument, a delimiter to use instead of a comma (,). Using a different delimiter however, somewhat defeats the purpose of CSV as an easy way to exchange tabular data.

Don't be tempted to bypass fgetcsv() and just read a line in and explode()on the commas. CSV is more complicated than that, in order to deal with embedded commas and double quotes. Using fgetcsv( ) protects you and your code from subtle errors.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in PHP )

PHP code to write to a CSV file from MySQL query

Different versions of PHP - History and evolution of PHP

PHP code to import from CSV file to MySQL

Encrypting files using GnuPG (GPG) via PHP

PHP Warning: Unknown(): Unable to load dynamic library '/usr/local/php4/lib/php/extensions/no-debug ......

Send push notifications using Expo tokens in PHP

Decrypting files using GnuPG (GPG) via PHP

A Basic Example using PHP in AWS (Amazon Web Services)

Count occurrences of a character in a String in PHP

Error: Length parameter must be greater than 0

Password must include both numeric and alphabetic characters - Magento

Reading word by word from a file in PHP

Parent: child process exited with status 3221225477 -- Restarting

Convert a hex string into a 32-bit IEEE 754 float number in PHP

PHP file upload prompts authentication for anonymous users

Latest Articles (in PHP)