• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 251
  • Last Modified:

Read File And Output in Table

I am currently reading a file and displaying using this:

        $file = fopen($filename.".txt","r");
            while(! feof($file)) {
              echo fgets($file). "<br />";
        }

I need to modify this logic to support a new output format that would include a table (rather than just raw string).

The contents of the uploaded file will be like this::

team=nyy,player=arod,position=3b
team=nym,player=jreyes,position=ss
team=stl,player=apujols,position=1b
player=cargo,position=cf
team=pit,player=gjones

The expected HTML output should be in a table with header / value. I have provided an example JPG attached.

I also want to support an export feature that would output into a CSV format. I have provided an example CSV file.

Lines which are missing a header/value should simply be converted to empty (if possible).

This would be a great help for me. Please let me know what needs to be done.
example.JPG
example.csv
0
deharvy
Asked:
deharvy
  • 7
  • 4
  • 3
  • +1
2 Solutions
 
4e4enCommented:
$data = array();
$file = fopen($filename.".txt","r");
while(! feof($file)) {
$line = fgets($file);
$row = explode(',', $line);
$t = array();
foreach($row as $e) {
$r = explode('=',$e, 2);
$t[ $r[0] ] = $r[1];
}
$data[] = $t;
}

echo '<table>';
foreach( $data as $row ) {
echo '<tr>';
foreach($row as $k => $e) {
 echo '<td>',$e,'</td>';
}
echo '</tr>';
}
echo '</table>';

Open in new window

0
 
deharvyAuthor Commented:
Thank you for the quick response. I'm trying to test this but not getting good results. Will try further and let you know.
0
 
Aaron TomoskySD-WAN SimplifiedCommented:
Just a suggestion, switch to file_get_contents. Much easier than fopen
0
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

 
deharvyAuthor Commented:
4e4en,

Your suggested code works well for the most part as I'm able to see the table with values. I am only missing the top headers.

If you can help with that, would be greatly appreciated.
0
 
4e4enCommented:
$data = array();
$file = fopen($filename.".txt","r");
while(! feof($file)) {
$line = fgets($file);
$row = explode(',', $line);
$t = array();
foreach($row as $e) {
$r = explode('=',$e, 2);
$t[ $r[0] ] = $r[1];
}
$data[] = $t;
}

echo '<table>';

if( isset($data[0] ) ) {
echo '<tr>';
foreach($data[0] as $k => $e) {
 echo '<td>',$k,'</td>';
}
echo '</tr>';
}

foreach( $data as $row ) {
echo '<tr>';
foreach($row as $k => $e) {
 echo '<td>',$e,'</td>';
}
echo '</tr>';
}
echo '</table>';

Open in new window

0
 
deharvyAuthor Commented:
4e4en,

Your latest update works great and provides most header columns.

But it looks like it's looking at the first message to build the header columns and not the message that has most of the headers.

For example, if I was to switch my table to this, the information would end up in wrong column and blank headers. :

team=pit,player=gjones
player=cargo,position=cf
team=nyy,player=arod,position=3b
team=nym,player=jreyes,position=ss
team=stl,player=apujols,position=1b

What is the best way to ensure that all column headers are available and information is populated in the right column?

I can open up a new question if you like so your code is working for the format I originally provided.

Let me know.
0
 
Ray PaseurCommented:
Here is a slightly generalized solution.
http://www.laprbass.com/RAY_temp_deharvy.php

Outputs something like:
team   player  position
nyy     arod      3b
nym    jreyes    ss
stl      apujols   1b
empty cargo     cf
pit      gjones    empty

team,player,position
nyy,arod,3b
nym,jreyes,ss
stl,apujols,1b
empty,cargo,cf
pit,gjones,empty

<?php // RAY_temp_deharvy.php
error_reporting(E_ALL);

// TEST DATA FROM THE POST AT EE
$str = <<<ENDSTRING
team=nyy,player=arod,position=3b
team=nym,player=jreyes,position=ss
team=stl,player=apujols,position=1b
player=cargo,position=cf
team=pit,player=gjones
ENDSTRING;

// WHAT COLUMNS DO WE WANT TO CAPTURE?
$columns = array
( 'team'
, 'player'
, 'position'
)
;

// HOW DO WE MARK EMPTY COLUMNS
$empty = 'empty';



// PROCESS EACH LINE OF THE TEST DATA FOR THE TABLE
$htm = NULL;
$arr = explode(PHP_EOL, $str);
foreach ($arr as $txt)
{
    $htm .= aa($txt, $columns, $empty);
}

// CREATE THE TABLE HEADERS
$hdr = '<tr>';
foreach ($columns as $key)
{
    $hdr .= '<th>' . $key . '</th>';
}
$hdr .= '</tr>' . PHP_EOL;

// FINISH THE TABLE
$new = '<table>' . $hdr . $htm . '</table>' . PHP_EOL;
echo $new;



// PROCESS EACH LINE OF THE TEST DATA FOR THE CSV
$csv = NULL;
$arr = explode(PHP_EOL, $str);
foreach ($arr as $txt)
{
    $csv .= aa($txt, $columns, $empty, 'CSV');
}

// CREATE THE CSV HEADERS
$hdr = NULL;
foreach ($columns as $key)
{
    $hdr .= $key . ',';
}
$hdr = rtrim($hdr, ',') . PHP_EOL;

// FINISH THE CSV
$new = $hdr . $csv;
echo "<pre>";
echo $new;



// A FUNCTION TO RETURN A ROW FROM A CSV STRING OF KEY=>VALUE PAIRS
function aa($str, $columns, $empty, $ret='HTML')
{
    // INITIALIZE THE RETURN ARRAY
    $tmp = array();
    foreach ($columns as $key)
    {
        $tmp[$key] = $empty;
    }

    // SEPARATE AND STORE THE KEY=>VALUE PAIRS
    $arr = explode(',', $str);
    foreach ($arr as $kvp)
    {
        $kvp = explode('=', $kvp);
        $tmp[$kvp[0]] = $kvp[1];
    }

    if ($ret == 'HTML')
    {
        // CREATE THE TABLE ROW STRING
        $row = '<tr>';
        foreach ($columns as $key)
        {
            $row .= '<td>' . $tmp[$key] . '</td>';
        }
        $row .= '</tr>' . PHP_EOL;
        return $row;
    }

    if ($ret == 'CSV')
    {
        // CREATE THE CSV STRING
        $csv = NULL;
        foreach ($columns as $key)
        {
            $csv .= $tmp[$key] . ',';
        }
        $csv = rtrim($csv, ',') . PHP_EOL;
        return $csv;
    }
}

Open in new window

0
 
deharvyAuthor Commented:
Ray_Paseur,

Thanks, this would probably be a good solution for the my csv output; so that's a piece of the puzzle.

Just think I need a little update to 4e4en's solution to be finished.

Will continue trying to tweak in the meantime.

0
 
Ray PaseurCommented:
Click the link I posted above, then use "view source" to see what the script created.  Thanks.
0
 
4e4enCommented:
$data_tpl = array( 'team'=>null, 'player'=>null, 'position'=>null );
$data = array();
$file = fopen($filename.".txt","r");
while(! feof($file)) {
$line = fgets($file);
$row = explode(',', $line);
$t = $data_tpl;
foreach($row as $e) {
$r = explode('=',$e, 2);
$t[ $r[0] ] = $r[1];
}
$data[] = $t;
}

echo '<table>';

if( isset($data[0] ) ) {
echo '<tr>';
foreach($data[0] as $k => $e) {
 echo '<td>',$k,'</td>';
}
echo '</tr>';
}

foreach( $data as $row ) {
echo '<tr>';
foreach($row as $k => $e) {
 echo '<td>',$e,'</td>';
}
echo '</tr>';
}
echo '</table>';

Open in new window

0
 
deharvyAuthor Commented:
4e4en,

Is there a way to do this without defining $data_tpl with static values? Meaning, is there a way to create the array dynamically?

I ask because some data might introduce new columns such as:

team=tb,player=sfuld,rank=2

If too much work (or will totally change the code), this will work for me as is and I'll use static columns. Just let me know if it can be done dynamically.
0
 
4e4enCommented:
to do what you are suggesting would require loop trought $data to collect all column names.

$data_tpl = array();
$data = array();
$lines = array();

$file = fopen($filename.".txt","r");
while(! feof($file)) {
  $line = fgets($file);
  $row = explode(',', $line);

  $t = array();
  foreach($row as $e) {
    $r = explode('=',$e, 2);
    $t[ ] = $r;
  }

  $lines[] = $t;
}

foreach( $lines as $line ) {
  $data_tpl = array_merge( $data_tpl, array_keys( $line ) );
}

foreach( $lines as $line ) {
$t = $data_tpl;
foreach( $line as $r) {
 $t[ $r[0] ] = $r[1];
}
$data[] = $t;
}


echo '<table>';

if( isset($data[0] ) ) {
echo '<tr>';
foreach($data[0] as $k => $e) {
 echo '<td>',$k,'</td>';
}
echo '</tr>';
}

foreach( $data as $row ) {
echo '<tr>';
foreach($row as $k => $e) {
 echo '<td>',$e,'</td>';
}
echo '</tr>';
}
echo '</table>';

Open in new window

0
 
Ray PaseurCommented:
some data might introduce new columns

This question has become a moving target and it's now something you might want to hire a developer to build for you.  We can answer questions that have some fairly well-bounded scope but we cannot write your programming for you for free.  I showed you a generalized solution based on the original question.  Using that you can modify the $columns array to meet your requirements.  But if you do not know how to do that immediately, you either need a developer or you need to take a month or three to learn PHP.  I highly recommend this book:
http://www.sitepoint.com/books/phpmysql4/

Anyway your original question is answered with a code example and a link to an online demonstration script that shows you how the code example works.  Best of luck with your project. ~Ray
0
 
deharvyAuthor Commented:
Thanks for all your help!
0
 
deharvyAuthor Commented:
Ray,

I understand your stance and therefore closed the question. You are right, it has been answered and the assistance given has put me in a good position.

---------------

4e4en,

Appreciate all your assistance these last couple days.
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.

Join & Write a Comment

Featured Post

Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

  • 7
  • 4
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now