List directory files in a table using php

Asked

Viewed 1,554 times

0

I have this php and html code that lists files from a folder, but I would like to put the results in a table, but for each row is being repeated the column title, Directoryiterator managed to solve, follows the updated code:

   <head>
<style>
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

tr:nth-child(even) {
    background-color: #dddddd;
}
</style>
</head>
<body>  

<?php


$path = "arquivos/";


echo "<h2>Lista de Arquivos:</h2><br />";
foreach (new DirectoryIterator($path) as $fileInfo) {
        if($fileInfo->isDot()) continue;

    echo "<table>

    <tr>
    <th>Nome</th>
    </tr>
    <tr>
    <td><a href='".$path.$fileInfo->getFilename() ."'>".$fileInfo->getFilename()."</a><br /></td>
    </tr>

</table>";
}
?>
</body>
</html>

<?php
  • First, remove the <tr> which has the name of the repeat loop column if you do not want it to repeat itself; second, search on DirectoryIterator of PHP.

  • Solved no! @Andersoncarloswoss

  • @Andersoncarloswoss the Directoryiterator managed to understand and solved, but the column name keeps repeating

1 answer

3


You will create only one table and a line of titles, so you can’t repeat this, just like you can’t repeat the table (</table>).

Example:

<?php

$path = "arquivos/";

// Título
echo "<h2>Lista de Arquivos:</h2><br />";

// Abre a tabela, cria títulos
echo "<table>";
echo "<tr> <th>Nome</th> </tr>";

// Loop que gera registros
foreach (new DirectoryIterator($path) as $fileInfo) {

    if($fileInfo->isDot()) continue;

    // Imprime linhas de registros
    echo "<tr>
            <td>
                <a href='".$path.$fileInfo->getFilename() ."'>".$fileInfo->getFilename()."</a><br/>
            </td>
          </tr>";
}

// Fecha a tabela
echo "</table>";

?>
  • I’ll test here, vlw

  • Worked perfectly!

  • 1

    @Miguelsilva the most important thing is you understand ! If you have questions, just let us know ! :)

  • it is possible to add one more column to show file size?

  • I’ll try to add

  • 1

    Yes, there is, child inside <tr> title, the <th>Tamanho</th>, and creates a column <td> next to the one you already have. The size, you can use the filesize.

  • Thank you very much! vlw.

  • sorry, I couldn’t get the size printed, I can add the column and stuff, but I couldn’t get the size printed if you can help me. vlw

  • 1

    @Miguelsilva Creates a new question, so it makes it easier for me to see what you’ve done, how you’re doing it, and how you can do it... Doing it for the comment is bad, and it’s not even the right one ! ;)

  • Okay, I’ll do it

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.