The following code will list all the file in a directory
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle)))
{
if (($file != ".")
&& ($file != ".."))
{
$thelist .= '<LI><a href="'.$file.'">'.$file.'</a>';
}
}
closedir($handle);
}
?>
<P>List of files:</p>
<UL>
<P><?=$thelist?></p>
</UL>
While this is very simple code it does the job.
I'm now looking for a way to list ONLY files that have .xml (or .XML) at the end, how do I do that?
You can extend the RecursiveFilterIterator class like this:
Now you can instantiate RecursiveDirectoryIterator with path as an argument like this:
This will list files under the current folder only.
To get the files in subdirectories also, pass the $iterator ( ExtensionFIlter Iterator) to RecursiveIteratorIterator as argument:
Now run the foreach loop on this iterator. You will get the files with specified extension
Note:-- Also make sure to run the ExtensionFilter before RecursiveIteratorIterator, otherwise you will get all the files
LIST FILES and FOLDERS in a directory (Full Code):
p.s. you have to uncomment the 5th line if you want only for specific extensions
You'll be wanting to use
glob()
Example:
You can also use the recursive variants of the iterators to traverse an entire directory hierarchy.
A simple way to look at the extension using substr and strrpos
Simplest answer is to put another condition
'.xml' == strtolower(substr($file, -3))
.But I'd recommend using
glob
instead too.