0

I have a CSV file with an initial header row and an unknown number of rows. The row format is:

name_data, email_data, cell_data, dob_data

I'd like to open the CSV file and then depict the data from the last entered row in a table, like this:

Name: name_data
Email: email_data
Cell: cell_data
D.O.B.: dob_data

I'm thinking I can use fgetcsv() but I'm not sure how to parse the data once I get it.

Any ideas?

Thanks - Joe

Joe Lowery
  • 562
  • 11
  • 26
  • example one on the maual page for fgetcsv is a great start –  Jul 10 '13 at 02:32
  • 1
    [What you want is tail information: Click Here](http://stackoverflow.com/a/16999819/1226894) – Baba Jul 10 '13 at 02:49

2 Answers2

7

Seems inefficient to parse every line of the file with fgetcsv() when you only care about the first and last line. As such, I'd use file() and str_getcsv():

$rows = file('data.csv');
$last_row = array_pop($rows);
$data = str_getcsv($last_row);
// loop and output data

Note: You can use the same logic for the headers by parsing $rows[0].

Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
  • The trade off from my version and yours is that your is piggish with space and mine is piggish with processor time. My second approach should be a good compromise. – Orangepill Jul 10 '13 at 02:46
  • Pretty sure this is even slower than parsing every line. – Robo Robok Dec 27 '22 at 17:08
0
$fp = fopen("csvfile.csv", "r");
// read all each of the records and assign to $rec;
while ($rec = fgetcsv($fp)){} 
?>
// rec will end up containing the last line
<table>
<tr><td>Name:</td><td><?= $rec[0] ?></td></tr>
<tr><td>Email : </td><td><?= $rec[1] ?></td></tr>
<tr><td>Cell :</td><td> <?= $rec[2] ?></td></tr>
<tr><td>D.O.B :</td><td> <?= $rec[3] ?></td></tr>
</table>

or if you anticipate the file being really long you can avoid having to walk each record by positioning the file pointer twice the maximum record length from the end of the file and then walking the record set.

$filesize = filesize("csvfile.csv");
$maxRecordLength = 2048;
$fp = fopen("csvfile.csv", "r");
// start near the end of the file and read til the end of the line
fseek($fp, max(0, $filesize - ($maxRecordLength *2));
fgets($fp);
// then do same as above
while ($rec = fgetcsv($fp)){}
?>
<table>
<tr><td>Name:</td><td><?= $rec[0] ?></td></tr>
<tr><td>Email : </td><td><?= $rec[1] ?></td></tr>
<tr><td>Cell :</td><td> <?= $rec[2] ?></td></tr>
<tr><td>D.O.B :</td><td> <?= $rec[3] ?></td></tr>
</table>
Orangepill
  • 24,500
  • 3
  • 42
  • 63