PHP想要遍历文件夹中文件夹所在的文件夹中的所有文件

时间:2016-02-21 03:31:06

标签: php

所以基本上我有包含文件夹的文件夹,在这些文件夹中我有

一些图片.jpg和一些txt文件

所以我想遍历这些文件夹,然后循环遍历里面的所有文件,并通过Javascript将它们附加到div

到目前为止,我将尝试这样的事情 只需要一些PHP建议,基本上这是一个正确的方法来做到这一点

<?php
    $directory = '/path/to/files';

    if (! is_dir($directory)) {
        exit('Invalid diretory path');
    }    

    foreach (scandir($directory) as $file // $file needs to be replaced with $folder for examle) {
        if ('.' === $file) continue; //what is this doing
        if ('..' === $file) continue; // and what is this doing

         //get path of the current folder via PHP
         // create the div with classes and id via javascript 
         // i know javascript so i skip this part

        foreach (scandir($directory) as $file) {
        if ('.' === $file) continue;
        if ('..' === $file) continue;

        //append img with src='php given path' and some classes
        //append some 'html h3' and some 'html p' and one 'html button'
        }
        //append the div with the html tags to a particular div i want
        // all  explained in '//' i can do via javascript so i need only help with PHP
    }


?>

我认为在第一次循环中我必须删除

if ('.' === $file) continue; 
 if ('..' === $file) continue;

1 个答案:

答案 0 :(得分:0)

如果结构如你所描述的那么简单,那么看一下glob

if (! is_dir($directory)) {
    exit('Invalid diretory path');
}    

foreach (glob($directory . '/*', GLOB_ONLYDIR) as $folder) {

     echo $folder . PHP_EOL; // this is a debug output. You do not need it

     // full path to folder is in $folder
     //get path of the current folder via PHP
     // create the div with classes and id via javascript 
     // i know javascript so i skip this part

    foreach (glob($folder . '/*.{jpg,txt}',GLOB_BRACE) as $file) {

        echo $file . PHP_EOL; // this is a debug output. You do not need it

        // Full path to image is in $file
        //append img with src='php given path' and some classes
        //append some 'html h3' and some 'html p' and one 'html button'
    }
    //append the div with the html tags to a particular div i want
    // all  explained in '//' i can do via javascript so i need only help with PHP
}