tags:

views:

121

answers:

5

The following code will list all the file in a directy

<?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 it job.

I'm now looking for a way to list ONLY file that have .xml (or .XML) at the end, how do I do that?

Code is appreciate, thanks!

jess

+5  A: 

You'll be wanting to use glob()

http://uk2.php.net/glob

Example:

$files = glob('/path/to/dir/*.xml');
DavidYell
i'm not a PHP programmer, I'm an old C programmer. Where if the code am I adding that?
Jessica
@Jessica you completely replace your code with that single line. It will return an array of all files paths having an xml extension. You can iterate over that with `foreach` to build your HTML list then.
Gordon
+1 Awesome answer. I didn’t know about `glob()` and will definitely be using this a lot from now on. Thanks!
Mathias Bynens
+1  A: 
$it = new RegexIterator(new DirectoryIterator("."), "/\\.xml\$/i"));

foreach ($it as $filename) {
    //...
}

You can also use the recursive variants of the iterators to traverse an entire directory hierarchy.

Artefacto
In PHP >= 5.3 you could also use the GlobIterator: http://de3.php.net/manual/en/class.globiterator.php
Gordon
A: 

In PHP5, you can just use scandir() to get the list of files in a directory as an array. Then just filter it for .xml files.

Here’s a helper function:

function file_list($d, $x){ 
 foreach(array_diff(scandir($d), array('.', '..')) as $f) if (is_file($d . '/' . $f) && (($x) ? ereg($x . '$' , $f) : 1)) $l[] = $f;
 return $l; 
}

// Use as follows
$files = file_list('/var/www/html/dir', '.xml');
Mathias Bynens
A: 

Simplest answer is to put another condition '.xml' == strtolower(substr($file, -3)).

But I'd recommend using glob instead too.

streetpc
A: 
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>';
        }
    }
    closedir($handle);
}

A simple way to look at the extension using substr and strrpos

Bob Fincheimer