Simplify your business
Tuesday, 7 October 2008 1:06 pm

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.

Posted in PHP, Programming, Tips by Ivan
Blinklist icon Del.iocio.us icon Furl icon Reddit icon Technorati icon Yahoo! icon

Got something to say?

To protect your privacy, your email address will not be displayed.





Some basic rules for commenting:

  • Watch your language.
  • Keep comments on-topic and relevant.
  • You can use basic XHTML tags for formatting and linking but not bbcode.
  • Comments are moderated, so don't double post if your comment doesn't appear immediately.
  • Please proof-read your comments for spelling and grammar mistakes.
  • Watch your language.