2

I have a folder in which I have some files and sub-folders. I need to return the names of the files or relative address (if the file is in sub-folder) that have a given extension, for example .html.

For example this is structure of given folder:

  • /text/something.ncx
  • /text/123.html
  • content.opf
  • toc.ncx
  • Flow_0.html
  • Flow_1.html
  • Flow_2.html

So the code should return this (in an array ideally):

  • text/123.html
  • Flow_0.html
  • Flow_1.html
  • Flow_2.html

It's just pulling out names with .html extension, but I really don't how to solve this.

Ben
  • 51,770
  • 36
  • 127
  • 149
Lukáš Jelič
  • 529
  • 3
  • 8
  • 22
  • possible duplicate: http://stackoverflow.com/questions/3062154/php-list-of-specific-files-in-a-directory – tereško Nov 27 '12 at 23:05
  • possible duplicate: http://stackoverflow.com/questions/3226519/use-php-scandirdir-and-get-only-images – tereško Nov 27 '12 at 23:06

4 Answers4

12

You could use a RecursiveDirectoryIterator to get all files recursively, then filter the result with a RegexIterator to iterate over only the *.html files. To get the relative adress, RecursiveDirectoryIterator::getSubPathname() can be used.

$directory  = '../path/to/your/folder';
$all_files  = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
$html_files = new RegexIterator($all_files, '/\.html$/');

foreach($html_files as $file) {
    echo $html_files->getSubPathname(), PHP_EOL;
}

If you really need and array (with iterable objects you often don't), you can easily build one up in the foreach rather than echo-ing each subpath.

salathe
  • 51,324
  • 12
  • 104
  • 132
2

To list files from folder (change $directory value to your preffered dirname and @ $files change your extension from .txt to preffered one.

$directory = "../images/team/harry/";


$files = glob($directory . "*.txt");


foreach($files as $file)
{
echo $file;
}
richardev
  • 976
  • 1
  • 10
  • 33
0

You can use glob function

glob('*.html')
Slawek
  • 583
  • 3
  • 9
-1

you can simply use this

<h1>

$Dir = 'you dir/';
$File = scandir($Dir);
$Type = pathinfo($File[$x],PATHINFO_EXTENSION);
if (strtolower($Type) === 'html'){
         echo $File;
}
<H2>
Tomas
  • 1
  • 1