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?
The scandir() function in PHP is an inbuilt function that is used to return an array of files and directories of the specified directory. The scandir() function lists the files and directories which are present inside a specified path.
PHP using scandir() to find folders in a directory The scandir function is an inbuilt function that returns an array of files and directories of a specific directory. It lists the files and directories present inside the path specified by the user.
PHP Read File - fread() The fread() function reads from an open file. The first parameter of fread() contains the name of the file to read from and the second parameter specifies the maximum number of bytes to read.
The glob() function returns an array of filenames or directories matching a specified pattern.
You'll be wanting to use glob()
Example:
$files = glob('/path/to/dir/*.xml');
if ($handle = opendir('.')) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != ".." && strtolower(substr($file, strrpos($file, '.') + 1)) == 'xml') { $thelist .= '<li><a href="'.$file.'">'.$file.'</a></li>'; } } closedir($handle); }
A simple way to look at the extension using substr and strrpos
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With