PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 2, 2022

[FIXED] how to create html table in php

 August 02, 2022     html, html-table, php     No comments   

Issue

I have the following snippet of code that basically uses explode to split out these values:

<?php
$data=array();
$Inputfile = file("prod.txt");
foreach ($Inputfile as $line){
   $pieces = explode(";", $line);
   echo $pieces[0];
   echo $pieces[1];
   echo $pieces[2];
   echo $pieces[3];
//print_r($line);
}
?>

Data: (prod.txt)

PREFIX=abc;PART=null;FILE=/myprojects/school/out/data/feed_abc_2010120810.gz2
PREFIX=efg;PART=sdsu;FILE=mail_efg.dat.2010120810.gz2

Can someone show me how to put this in an HTML table dynamically, like this?? Is there an easy way to do this? Thanks.

PREFIX  PART   FILE
abc     null   /myprojects/school/out/data/feed_abc_2010120810.gz2
efg     sdsu   mail_efg.dat.2010120810.gz2

Solution

This should be flexible enough and won't require any hard-coded pair names:

<?php

$lines = preg_split('~\s*[\r\n]+\s*~', file_get_contents('prod.txt'));

foreach($lines as $i => $line) {
    $pairs = explode(';', $line);
    foreach($pairs as $pair) {
        list($column, $value) = explode('=', $pair, 2);
        $columns[$column] = true;
        $rows[$i][$column] = $value;
    }
}

$columns = array_keys($columns);


echo '<table><thead><tr>';

foreach($columns as $column) {
    echo '<th>'.$column.'</th>';
}

echo '</tr></thead><tbody>';

foreach($rows as $row) {
    echo '<tr>';
    foreach($columns as $column) {
        echo '<td>'.$row[$column].'</td>';
    }
    echo '</tr>';
}
echo '</tbody></table>';

?>


Answered By - Kevin
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing