Page 1 of 1

split() and file() contents into a table

Posted: Sat Oct 14, 2006 7:45 pm
by joannemac1
feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Using a comma delimited file ("lab13.txt), I need to split by (,) and then output the results into a table that is 6 columns and 10 rows.  I got as far as the "<td>". How do I get the table, the TR and the TD?

Code: Select all

<?php

$fileContentsArray=file("lab13.txt");

foreach($fileContentsArray as $one_persons_data)
{
	$A1=split(",", $one_persons_data);
	
foreach($A1 as $contents)
	echo "<td>" .$contents . "</td>";
}

}

?>

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Sat Oct 14, 2006 7:52 pm
by feyd
echo the opening <tr> before the inner foreach, and closing </tr> after it. The <table> goes before the outer foreach, and closing </table> goes after it.

Beware that split() uses regular expressions. Since you don't need their power here, I'd suggest using explode() instead.

Posted: Sat Oct 14, 2006 7:57 pm
by Cameri
You might want to try something like:

Code: Select all

<?php
// variables
$filename = "lab13.txt";

$file_contents = file($filename);
if (count($file_contents)>0) {
  echo "<table>\n";
  foreach($file_contents as $current_line){
    $data_fields=explode(",", $current_line);
    if (count($line_data)>0){
      echo "<tr>\n";
      foreach($data_fields as $field)
        echo "<td>" .$field . "</td>\n";
      }
      echo "</tr>";
    }
  }
  echo "</table>\n";
} else {
  echo "File is empty, no table generated...";
}
?>