How to Read Data From CSV File In PHP

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.

 

Advertisements
Categories: PHP

One thought on “How to Read Data From CSV File In PHP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s