Thursday, 4 March 2010

PHP and SCV files

PHP has a lovely function which reads a line of a .csv file into an array called fgetcsv.

Given a .csv file like this:

Line One, 001, £11
Line Two, 002, £22
Line Three, 003, £33
Line Four, 004, £44
Line Five, 005, £55

We can iterate through the .csv file using this php code:

<?php
  // Open a file for reading.
  $file_handle = fopen("test.csv", "r");
  // Start the table html.
  echo '<table cellspacing="2" cellpadding="2" border="1">';
  // Work through each line of the file
  while (!feof($file_handle) ) {
    // Get each line and convert it into an array
    $line_of_text = fgetcsv($file_handle, 1024);
    // Use each array as the contents for the line of the table
    print("<tr>");
    print("<td>".htmlentities($line_of_text[0])."</td>");
    print("<td>".htmlentities($line_of_text[1])."</td>");
    print("<td>".htmlentities($line_of_text[2])."</td>");
    print("</tr>");
  }
  // End the table html
  echo "</table>";
  // Close the file.
  fclose($file_handle);
?>

But if we don't know how many records are in each line then we can use:

<?php
  $file_handle = fopen("test.csv", "r");
  echo '<table cellspacing="2" cellpadding="2" border="1">';
  while (!feof($file_handle) ) {
    $line_of_text = fgetcsv($file_handle, 1024);
    print("<tr>");
    foreach ($line_of_text as $cell) {
      print("<td>".htmlentities($cell)."</td>");
    }
    print("</tr>");
  }
  echo "</table>";
  fclose($file_handle);
?>

Which is much nicer. But does sometimes mess up so you could check that the returned line is actually an array before processing it as it'll fall over if there are dodgy carriage returns and such like. So:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title></title>
  </head>
  <body>
    <?php
      $file_handle = fopen("test.csv", "r");
      echo '<table cellspacing="1" cellpadding="1" border="1">';
      while (!feof($file_handle) ) {
        $line_of_text = fgetcsv($file_handle, 1024);
        if(is_array($line_of_text)){
          print("<tr>");
          foreach ($line_of_text as $cell) {
            print("<td>".htmlentities($cell)."</td>");
          }
          print("</tr>");
        }
      }
      echo "</table>";
      fclose($file_handle);
    ?>
  </body>
</html>

Which'll give us

Line One 001 £11
Line Two 002 £22
Line Three 003 £33
Line Four 004 £44
Line Five 005 £55