Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP list of specific files in a directory

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?

like image 885
Jessica Avatar asked Jun 17 '10 13:06

Jessica


People also ask

How do I get a list of files in a directory in PHP?

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.

How can I get a list of all the subfolders and files present in a directory using PHP?

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.

How do I view a file in PHP?

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.

What is PHP glob?

The glob() function returns an array of filenames or directories matching a specified pattern.


2 Answers

You'll be wanting to use glob()

Example:

$files = glob('/path/to/dir/*.xml'); 
like image 180
David Yell Avatar answered Oct 08 '22 12:10

David Yell


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

like image 23
Bob Fincheimer Avatar answered Oct 08 '22 13:10

Bob Fincheimer