How to get the file name under a folder?

前端 未结 7 761
日久生厌
日久生厌 2020-12-18 01:43

Suppose I have a directory look like:

ABC
|_ a1.txt
|_ a2.txt
|_ a3.txt
|_ a4.txt
|_ a5.txt

How can I use PHP to get these file names to an

相关标签:
7条回答
  • 2020-12-18 02:13

    If your text files is all that you have inside of the folder, the simplest way is to use scandir, like this:

    <?php
    $arr=scandir('ABC/');
    ?>
    

    If you have other files, you should use glob as in Lawrence's answer.

    0 讨论(0)
  • 2020-12-18 02:17

    You can use the glob() function:

    Example 01:

    <?php
      // read all files inside the given directory
      // limited to a specific file extension
      $files = glob("./ABC/*.txt");
    ?>
    

    Example 02:

    <?php
      // perform actions for each file found
      foreach (glob("./ABC/*.txt") as $filename) {
        echo "$filename size " . filesize($filename) . "\n";
      }
    ?>
    

    Example 03: Using RecursiveIteratorIterator

    <?php 
    foreach(new RecursiveIteratorIterator( new RecursiveDirectoryIterator("../")) as $file) {
      if (strtolower(substr($file, -4)) == ".txt") {
            echo $file;
      }
    }
    ?>
    
    0 讨论(0)
  • 2020-12-18 02:22

    Here is the most Efficient way based on this article's benchmarks:

    function getAllFiles() {
        $files = array();
        $dir = opendir('/ABC/');
        while (($currentFile = readdir($dir)) !== false) {
            if (endsWith($currentFile, '.txt'))
                $files[] = $currentFile;
        }
        closedir($dir);
        return $files;
    }
    
    function endsWith($haystack, $needle) {
        return substr($haystack, -strlen($needle)) == $needle;
    }
    

    just use the getAllFiles() function, and you can even modify it to take the folder path and/or the extensions needed, it is easy.

    0 讨论(0)
  • 2020-12-18 02:23

    scandir lists files and directories inside the specified path.

    0 讨论(0)
  • 2020-12-18 02:30

    Aside from scandir (@miku), you might also find glob interesting for wildcard matching.

    0 讨论(0)
  • 2020-12-18 02:34

    Try this:

    if ($handle = opendir('.')) {
        $files=array();
        while (false !== ($file = readdir($handle))) {
            if(is_file($file)){
                $files[]=$file;
            }
        }
        closedir($handle);
    }
    
    0 讨论(0)
提交回复
热议问题