Forum Moderators: coopster

Message Too Old, No Replies

Help CSV in PHP

How do I display a 4x3 csv table?

         

zacreyna

8:28 am on Feb 4, 2008 (gmt 0)

10+ Year Member



My csv file looks like this.

John,Doe,Smith,M,20
Jane,Dane,Smith,F,20
Joe,Shmo,Baggins,M,30

I grabbed this code from weberdev and edited like this:

<?php
//stock quote script
//this is the url for Microsoft's stock quote , we are opening it for reading
$fp = fopen ("file.csv","r");
//this uses the fgetcsv function to store the quote info in the array $data
$data = fgetcsv ($fp, 1000, ",")
?>
<!-- this is our table which displays the stock info -->
<!-- we access the individual items by using $data[0]-->
<table>
<tr><td>First Name:</td><td><?php echo $data[0]?></td></tr>
<tr><td>Middle Name:</td><td><?php echo $data?></td></tr>
<tr><td>Last Name:</td><td><?php echo $data[2]?></td></tr>
<tr><td>Sex:</td><td><?php echo $data[3]?></td></tr>
<tr><td>Age:</td><td><?php echo $data[4]?></td></tr>
</table>
<?php
//close the filehandle $fp
fclose ($fp);
?>

When I view the page it looks like this:

First Name: John
Middle Name: Doe
Last Name: Smith
Sex: M
Age: 20

Where's the rest of the info?
Anyways, how can I get this to be displayed like this?

First Name Middle Name Last Name Sex Age
John Doe Smith M 20
Jane Dane Smith F 20
Joe Shmo Baggina M 30

[1][edited by: jatar_k at 2:24 pm (utc) on Feb. 4, 2008]
[edit reason] no urls thanks [/edit]

surrealillusions

11:00 am on Feb 4, 2008 (gmt 0)

10+ Year Member



You'll need to re-write your tables to make it show up the way you want.

Your tr's make a new table row, hence the data been on seperate lines and not in coloumns.

I'm not sure how to repeat the sections with the data your pulling out of the text file though..so cant help you with that. But since your only echoing the data once, it will only show the most recent data or at least the data at the top of the text file, thats what i would think anyway by the looks of it.

Hope that helps

:)

deMorte

1:34 pm on Feb 4, 2008 (gmt 0)

10+ Year Member



I'm not very familiar with operating CSV -files on PHP but this is what I figured from PHP.net manual on fgetcsv.

You should do a while-loop on your fgetcsv as such:


<table>
<tr>
<td>First Name:</td><td>Middle Name:</td>
<td>Last Name:</td><td>Sex:</td><td>Age:</td>
</tr>
<?php
while(($data = fgetcsv($handle, 1000, ","))!== FALSE) {
?>
<tr>
<td><?php echo $data[0]?></td>
<td><?php echo $data[1]?></td>
<td><?php echo $data[2]?></td>
<td><?php echo $data[3]?></td>
<td><?php echo $data[4]?></td>
</tr>
}
?>
</table>

I'm basically copy-pasting this from PHP.net, so maybe you should check it out.
I'd link you there, but I guess it's against the rules.