1.9. Parsing Comma-Separated Data
Problem
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.
Solution
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");Discussion
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.
See Also
Documentation on fgetcsv( ) at