Parsing CSV files with PHP

A couple of months ago I downloaded a CSV file from Google containing the stats of my sites. I decided to turn it into an HTML table using PHP. Here's how it's done:


   $csv = fopen('top-search-queries.csv', 'r') or die ("Can't open file.");
   echo '<table border="1" cellspacing="2" cellpadding="3">' . "\n";
   while($csv_line = fgetcsv($csv)) {
       echo "<tr>\n";
       for($i = 0, $j = count($csv_line); $i < $j; $i++) {
           echo '<td>' . htmlentities($csv_line[$i]) . '</td>' . "\n";
       echo "</tr>\n";
   echo "</table>\n";
   fclose($csv) or die("Can't close file");


I used the fgetcsv() function to parse the CSV file line by line. It's a really straightforward function, but it's very useful in cases like this.

This entry was posted in , by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.