Display last entered data from CSV file in PHP? [closed]

为君一笑 提交于 2019-12-01 14:42:08

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].

$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>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!