Bren
Bren

Reputation: 615

Convert a text file containing lines of comma-separated values into an HMTL table

I am using file_get_contents() to import a text file. In the text file, the format goes as below (example):

3434,83,8732722
834,93,4983293
9438,43933,34983

and so forth... basically it follows the pattern: integer, comma to split it, second integer, another comma to split it, third integer, then a new line begins.

I need to get this into a table with the format following accordingly. So in other words, I would have a 3 column table and each new line in the text file would be a new row in the table.

This must be transcoded into a simple html table with <table> <tr> and <td>

I have never worked with multidimensional arrays and splitting text with that.

All I was able to do was use explode("\n", $file); to seperate the lines, other than that, I have no clue how to split it again, nor organize it in an efficient way to make it into a neat table.

Upvotes: 0

Views: 4744

Answers (3)

Atul Rai
Atul Rai

Reputation: 350

You can do following :

$filename = 'abc.txt';
$content = file_get_contents($filename);
$explodedByBr = explode('<br/>', $content);
$table = "<table border='1'>";
foreach ($explodedByBr as $brExplode) {
  $explodedByComma = explode(',', $brExplode);

  $table .= "<tr>";
  foreach ($explodedByComma as $commaExploded) {
    $table .= "<td>" .$commaExploded. "</td>";
  }
  $table .= "<tr/>";
}
$table .= "</table>";

echo $table;

abc.txt has data in following format :

3434,83,8732722
834,93,4983293
9438,43933,34983

Upvotes: 1

web-nomad
web-nomad

Reputation: 6003

Try this:

Read the file into an array and then column'ize it by processing each line of the array by passing it through array_walk.

<?php
function addElements( &$v, $k ) {
    $v1 = explode( ',', $v ); // break it into array
    $v2 = '';
    foreach( $v1 as $element ) {
        $v2 .= '<td>'.$element.'</td>';
            // convert each comma separated value into a column
    }
    $v = '<tr>'.$v2.'</tr>'; // add these columns to a row and return
}

// read the whole file into an array using php's file method.
$file = file( '1.txt' );
// now parse each line of the array so that we convert each line into 3 columns.
// For this, i use array_walk function which calls a function, addElements, 
// in this case to process each element in the array.
array_walk( $file, 'addElements' );
?>
<html>
     <head></head>
     <body>
         <table border="0">
             <?php echo implode('',$file);?>
         </table>
     </body>
</html>

Hope it helps. See the php doc for file and array_walk. These are simple and convenient functions.

Upvotes: 0

Mihai Matei
Mihai Matei

Reputation: 24276

<?php
    $file = 'path/to/file.txt';
    echo '<table>';
    while(!feof($file)) {
        $line = fgets($file);

        echo '<tr><td>' . implode('</td><td>',explode(',',$line)) . '</td></tr>';
    }
    echo '</table>';
?>

Upvotes: 0

Related Questions