Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Read File And Output in Table

Posted on 2011-04-22
15
Medium Priority
?
249 Views
Last Modified: 2012-06-22
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
Comment
Question by:deharvy
  • 7
  • 4
  • 3
  • +1
15 Comments
 
LVL 4

Expert Comment

by:4e4en
ID: 35451679
$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
 

Author Comment

by:deharvy
ID: 35451778
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
 
LVL 39

Expert Comment

by:Aaron Tomosky
ID: 35451823
Just a suggestion, switch to file_get_contents. Much easier than fopen
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:deharvy
ID: 35452128
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
 
LVL 4

Expert Comment

by:4e4en
ID: 35453553
$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
 

Author Comment

by:deharvy
ID: 35453908
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
 
LVL 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 200 total points
ID: 35454008
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
 

Author Comment

by:deharvy
ID: 35454192
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
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 35454200
Click the link I posted above, then use "view source" to see what the script created.  Thanks.
0
 
LVL 4

Accepted Solution

by:
4e4en earned 1800 total points
ID: 35454255
$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
 

Author Comment

by:deharvy
ID: 35454330
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
 
LVL 4

Expert Comment

by:4e4en
ID: 35454383
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
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 35454666
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
 

Author Closing Comment

by:deharvy
ID: 35454687
Thanks for all your help!
0
 

Author Comment

by:deharvy
ID: 35454688
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

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When crafting your “Why Us” page, there are a plethora of pitfalls to avoid. Follow these five tips, and you’ll be well on your way to creating an effective page.
There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
In this tutorial viewers will learn how to embed Flash content in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: "<!DOCTYPE html>": Use the <object> tag to embed Flash content.: To specify that the object is Flash content, d…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Suggested Courses
Course of the Month20 days, 19 hours left to enroll

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question