Parsing comma-separated data in PHP
Saturday, 14 October 2006
It’s only recently that I discovered the PHP function fgetcsv(), which offers a quick and powerful way of handling CSV data, such as that exported by Excel and other spreadsheets.
Using fgetcsv(), the process of reading in a CSV file and printing the results in a HTML table is as simple as this:
$fp = fopen('test.csv', 'r') or die('cannot open file');
echo "<table>\n";
while ($line = fgetcsv($fp, 4096)) {
$max = count($line);
echo "<tr>\n";
for ($i = 0; $i < $max; $i++) {
echo "<td>{$line[$i]}</td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
fclose($fp) or die('cannot close file');
The real power of fgetcsv() is that it automatically handles the double quotes and any embedded commas which may be present in the source data.
|