split() and file() contents into a table

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
joannemac1
Forum Newbie
Posts: 4
Joined: Sat Oct 14, 2006 1:26 pm

split() and file() contents into a table

Post 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]
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
User avatar
Cameri
Forum Commoner
Posts: 87
Joined: Tue Apr 12, 2005 4:12 pm
Location: Santo Domingo, Dominican Republic

Post 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...";
}
?>
Post Reply