PHP list of specific files in a directory

142,982

Solution 1

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

Solution 2

You'll be wanting to use glob()

Example:

$files = glob('/path/to/dir/*.xml');

Solution 3

$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.

Solution 4

I use this code:

<?php

{
//foreach (glob("images/*.jpg") as $large) 
foreach (glob("*.xml") as $filename) { 

//echo "$filename\n";
//echo str_replace("","","$filename\n");

echo str_replace("","","<a href='$filename'>$filename</a>\n");

}
}


?>

Solution 5

you can mix between glob() function & pathinfo() function like below.

the below code will show files information for specific extension "pdf"

foreach ( glob("*.pdf") as $file ) {

    $file_info = pathinfo( getcwd().'/'.$file );

    echo $file_info['dirname'], "<br>";
    echo $file_info['basename'], "<br>";
    echo $file_info['extension'], "<br>";
    echo $file_info['filename'], "<br>"; 
    echo '<hr>';
}
Share:
142,982
Jessica
Author by

Jessica

Updated on August 24, 2020

Comments

  • Jessica
    Jessica over 3 years

    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?