<html>
<! GetFileByCSV.php                                           >
<! Chapter 10, Oracle Database XE PHP Web Programming         >
<! by Michael McLaughlin                                      >
<!                                                            >
<! This script demonstrates how to read a comma-separated     >
<! file into a recursively rendered table.                    >
<head>
<title>
  Chapter 10 : GetFileByCSV.php
</title>
</head>
<body>
<?php
  // Set the file name.
  $fname = realpath("csvfile.csv");

  // Declare an array to hold CSV values.
  $contents = array();

  // Check for a valid read-only file handle.
  if ($fp = fopen($fname,'r'))
  {
    // Read to end-of-file by CSV.
    while (!feof($fp))
      $contents[] = fgetcsv($fp,1000,",");

    // Close the open file handle.
    fclose($fp);
  }

  // Read and parse CSV file.
  print render_csv_to_table($contents);

  // Define function to render CSV file in HTML table.
  function render_csv_to_table($csv_array)
  {
    // Declare variable with table start.
    $out = "<table border=0 cellpadding=0 cellspacing=0>";

    // Loop through the rows.
    foreach ($csv_array as $key => $value)
    {
      // Prepend the open table row tag.
      $out .= "<tr>";

      // Loop through the columns and add HTML cell tags.
      foreach ($value as $skey => $svalue)
        $out .= "<td>".$svalue."</td>";

      // Append the close table row tag.
      $out .= "</tr>";
    }

    // Close HTML table.
    $out .= "</table>";

    // Return formatted CSV array.
    return $out;
  }
?>
</body>
</html>
