r/PHPhelp • • Nov 12 '22

CSV to HTML Table via Array not working

I am trying to turn my CSV file into a HTML Table

        echo "<pre>";

        $handle = fopen("quotes.csv", "r");
        while (($data = fgetcsv($handle)) !== FALSE) 
        {
        foreach (explode("\n", $data[0]) as $line) 
        {
            print_r(str_getcsv($line, "|"));
        }   
        }
        echo "</pre>";

This code creates an array as I was checking the format of the CSV

Array
(
    [0] => The old world is dying, and a new world struggles to be born; now is the time of monsters.
    [1] => Antonio Gramsci
    [2] => 1891-1937
    [3] => https://en.wikipedia.org/wiki/Antonio_Gramsci
    [4] => https://upload.wikimedia.org/wikipedia/commons/e/e6/Gramsci.png
    [5] => politics
)
Array
(
    [0] => They'll say we're disturbing the peace, but there is no peace. What really bothers them is that we are disturbing the war.
    [1] => Howard Zinn
    [2] => 1922-2010
    [3] => https://en.wikipedia.org/wiki/Howard_Zinn
    [4] => https://upload.wikimedia.org/wikipedia/commons/e/ef/Howard_Zinn%2C_2009_%28cropped%29.jpg
    [5] => politics
)

The table below tells me $data is not an array

<table>
    <tbody>
    <?php foreach($data as $row)
    {
        ?>
        <tr>
        <td><?=$row[0]?></td>
        <td><?=$row[1]?></td>
        <td><?=$row[2]?></td>
        <td><?=$row[3]?></td>
        <td><?=$row[4]?></td>
        <td><?=$row[5]?></td>
    </tr>
    <?php  } ?>
    
    </tbody>
</table>

So how will I put this array into the HTML table?

10 Upvotes

2 comments sorted by

6

u/AleatoricConsonance Nov 12 '22

Well, I took a crack at it. I think you're not getting quite what you think you're getting...

$handle = fopen("quotes.csv", "r");
$quotes = []; 
while (($data = fgetcsv($handle)) !== FALSE) 
{
    $quotes[] = $data;
}

This stores each row in an array "$quotes". Then just iterate over the array ...

<table>
<?php foreach ($quotes as $row) { ?>
<tr>
    <td><?= $row[0] ?></td>
</tr>
<?php } ?>
</table>

I've abbreviated the fragment. It's more robust if you throw the array $row into for-loop as well, that way you can add or remove columns from your CSV source and won't need to change your table rendering code.

2

u/moto_trip69 Nov 12 '22

Are you taking the php course from gio's youtube channel? This was exactly one of the mini-projects that was assigned... , maybe this could help. https://github.com/ggelashvili/learnphptherightway-project/tree/1.31