Madsen Madsen - 1 month ago 13
PHP Question

Display lines in reverse order fgetcsv

How do I display lines in reverse order?

CSV file:


column1;column2;column3

cell1;cell1;cell1

cell2;cell2;cell2

cell3;cell3;cell3


It should appear like this:


column1;column2;column3

cell3;cell3;cell3

cell2;cell2;cell2

cell1;cell1;cell1


Code:

if (($handle = fopen($path, 'r')) !== FALSE)
{
echo '<table class="table table-striped table-bordered"><thead>';
// Get headers
if (($data = fgetcsv($handle, 1000, ';')) !== FALSE)
{
echo '<tr><th>'.implode('</th><th>', $data).'</th></tr>';
}
echo '</thead><tbody>';
// Get the rest
while (($data = fgetcsv($handle, 1000, ';')) !== FALSE)
{
echo '<tr><td>'.implode('</td><td>', $data).'</td></tr>';
}
fclose($handle);
echo '</tbody></table>';
}


Thanks in advance.

Answer

Collect first

$collect = array();
while (($data = fgetcsv($handle, 1000, ';')) !== FALSE)
{
  $collect[]= '<tr><td>'.implode('</td><td>', $data).'</td></tr>';
}
echo implode(PHP_EOL,array_reverse($collect));

Reverse the array at the end.