PHP CSV showing in table

230 views Asked by At

I want to show this CSV File the same way as the picture but then in PHP. Right now I know how to show it if they were all under "A", but I'm stuck now on how to show it with more then one cell.

<?php
echo "<table border='1'>";
if (($handle = fopen("top10.csv", "r")) !== FALSE) {
    $data = fgetcsv($handle, 0, ",");
    while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
        echo "<tr>";
        $num = count($data);
        for ($i=0; $i < $num; $i++) {
            echo"<td>" . $data[$i] . "<br /> </td>";
        }
        echo "</tr>";
    }
    fclose($handle);
}
?> 

This is how I did it with 2 rows.

Image:

enter image description here

Result right now:

2

There are 2 answers

0
tftd On

You might want to use SplFileObject which can parse CSV files. For example:

$file = new SplFileObject("/path/to/your/csv/file.csv");
$file->setFlags(SplFileObject::READ_CSV);
$rows = "";
foreach ($file as $row) {
    list ($a, $b, $c, $d, $e, $f, $g, $h, $i, $j, $k, $l) = $row;

    $rows .= <<<HTML
<tr>
    <td>${a}</td>
    <td>${b}</td>
    <td>${c}</td>
    <td>${d}</td>
    <td>${e}</td>
    <td>${f}</td>
    <td>${g}</td>
    <td>${h}</td>
    <td>${i}</td>
    <td>${j}</td>
    <td>${k}</td>
    <td>${l}</td>
</tr>
HTML;
}

echo "<table>".$rows."</table>";

PHP Documentation

1
Ahosan Karim Asik On

you read file 2times in your code:

$data = fgetcsv($handle, 0, ",");// 1st  (just remove this line)
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) { // 2nd

and another solution try this:

echo "<table border=\"1\">";
$row=@explode("\n",@file_get_contents('test.csv'));
if(count($row)>0) foreach($row as $r){
    $col=@explode(",",$r);
    echo "<tr>";
    foreach($col as $c){
        echo "<td>$c</td>";
    }
    echo "</tr>";
}   
echo "</table>";