Display CSV file data using PHP

Hi There,

I have written the code below to read am reading the contents of a CSV file. The content in the CSV file has three colums with data and multiple rows:
content1, content2, content3
content1, content2, content3
content1, content2, content3

I need to display this as a table in a webpage where content1, content2 and content3 would be in their own cell. When displayed in the webpage there should be three rows. Any suggestions on how i can get this done?

See code below. Speedy response is very much appreciated.

$dir_name = "C:/apache/htdocs/E-Books.txt";
$fh = fopen($dir_name, "r");
$row = 1;

while(($data = fgetcsv($fh, 1000, ",")) !== FALSE)
{
    $num = count($data); // count the # of lines that exist
    $row++;  //increment the row variable to the next line
   
//output current line to the screen.
    for ($i=0; $i < $num; $i++)
      {
          echo $data[$i]."\n";
      }
}

//close file handler and delete file
fclose($fh);
motolanix1Asked:
Who is Participating?
 
jb1devConnect With a Mentor Commented:
Does this work.

$dir_name = "C:/apache/htdocs/E-Books.txt";
$fh = fopen($dir_name, "r");
$row = 1;

echo "<table>\n";
while(($data = fgetcsv($fh, 1000, ",")) !== FALSE)
{
    echo "<tr>\n";
    $num = count($data); // count the # of lines that exist
    $row++;  //increment the row variable to the next line
   
//output current line to the screen.
    for ($i=0; $i < $num; $i++)
      {
          echo "<td>\n";
          echo $data[$i]."\n";
          echo "</td>\n";
      }
    echo "</tr>\n";
}
echo "</table>\n";

//close file handler and delete file
fclose($fh);

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.