php – 如何获取文件夹下的文件名?

前端之家收集整理的这篇文章主要介绍了php – 如何获取文件夹下的文件名?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我的目录看起来像:
  1. ABC
  2. |_ a1.txt
  3. |_ a2.txt
  4. |_ a3.txt
  5. |_ a4.txt
  6. |_ a5.txt

如何使用PHP将这些文件名转换为数组,仅限于特定的文件扩展名并忽略目录?

您可以使用 glob()功能

例01:

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

例02:

  1. <?PHP
  2. // perform actions for each file found
  3. foreach (glob("./ABC/*.txt") as $filename) {
  4. echo "$filename size " . filesize($filename) . "\n";
  5. }
  6. ?>

例03:使用RecursiveIteratorIterator

  1. <?PHP
  2. foreach(new RecursiveIteratorIterator( new RecursiveDirectoryIterator("../")) as $file) {
  3. if (strtolower(substr($file,-4)) == ".txt") {
  4. echo $file;
  5. }
  6. }
  7. ?>

猜你在找的PHP相关文章