Liste PHP des fichiers spécifiques dans un répertoire

le code suivant listera tout le fichier dans un répertoire

<?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>

bien que ce soit un code très simple, il fait le travail.

je cherche maintenant un moyen de ne lister que les fichiers qui ont .xml (ou .XML) à la fin, comment dois-je faire?

42
demandé sur totallyNotLizards 2010-06-17 17:47:30

8 réponses

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);
}

Une simple façon de regarder le extension à l'aide de substr et strrpos

47
répondu Bob Fincheimer 2012-06-23 11:56:02

vous voudrez utiliser glob()

exemple:

$files = glob('/path/to/dir/*.xml');
181
répondu David Yell 2011-11-13 16:50:51
$it = new RegexIterator(new DirectoryIterator("."), "/\.xml$/i"));

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

vous pouvez également utiliser les variantes récursives des itérateurs pour parcourir toute une hiérarchie de répertoires.

9
répondu Artefacto 2010-06-17 13:49:59

LIST FILES and FOLDERS in a directory (code complet)):

p. S. vous devez décommenter la cinquième ligne si vous voulez seulement pour les extensions spécifiques

<?PHP
# The current directory
$directory = dir("./");

# If you want to turn on Extension Filter, then uncomment this:
### $allowed_ext = array(".sample", ".png", ".jpg", ".jpeg", ".txt", ".doc", ".xls"); 




## Description of the soft: list_dir_files.php  
## Major credits: phpDIRList 2.0 -(c)2005 Ulrich S. Kapp :: Systemberatung ::

$do_link = TRUE; 
$sort_what = 0; //0- by name; 1 - by size; 2 - by date
$sort_how = 0; //0 - ASCENDING; 1 - DESCENDING


# # #
function dir_list($dir){ 
    $i=0; 
    $dl = array(); 
    if ($hd = opendir($dir))    { 
        while ($sz = readdir($hd)) {  
            if (preg_match("/^\./",$sz)==0) $dl[] = $sz;$i.=1;  
        } 
    closedir($hd); 
    } 
    asort($dl); 
    return $dl; 
} 
if ($sort_how == 0) { 
    function compare0($x, $y) {  
        if ( $x[0] == $y[0] ) return 0;  
        else if ( $x[0] < $y[0] ) return -1;  
        else return 1;  
    }  
    function compare1($x, $y) {  
        if ( $x[1] == $y[1] ) return 0;  
        else if ( $x[1] < $y[1] ) return -1;  
        else return 1;  
    }  
    function compare2($x, $y) {  
        if ( $x[2] == $y[2] ) return 0;  
        else if ( $x[2] < $y[2] ) return -1;  
        else return 1;  
    }  
}else{ 
    function compare0($x, $y) {  
        if ( $x[0] == $y[0] ) return 0;  
        else if ( $x[0] < $y[0] ) return 1;  
        else return -1;  
    }  
    function compare1($x, $y) {  
        if ( $x[1] == $y[1] ) return 0;  
        else if ( $x[1] < $y[1] ) return 1;  
        else return -1;  
    }  
    function compare2($x, $y) {  
        if ( $x[2] == $y[2] ) return 0;  
        else if ( $x[2] < $y[2] ) return 1;  
        else return -1;  
    }  

} 

################################################## 
#    We get the information here 
################################################## 

$i = 0; 
while($file=$directory->read()) { 
    $file = strtolower($file);
    $ext = strrchr($file, '.');
    if (isset($allowed_ext) && (!in_array($ext,$allowed_ext)))
        {
            // dump 
        }
    else { 
        $temp_info = stat($file); 
        $new_array[$i][0] = $file; 
        $new_array[$i][1] = $temp_info[7]; 
        $new_array[$i][2] = $temp_info[9]; 
        $new_array[$i][3] = date("F d, Y", $new_array[$i][2]); 
        $i = $i + 1; 
        } 
} 
$directory->close(); 

################################################## 
# We sort the information here 
################################################# 

switch ($sort_what) { 
    case 0: 
            usort($new_array, "compare0"); 
    break; 
    case 1: 
            usort($new_array, "compare1"); 
    break; 
    case 2: 
            usort($new_array, "compare2"); 
    break; 
} 

############################################################### 
#    We display the infomation here 
############################################################### 

$i2 = count($new_array); 
$i = 0; 
echo "<table border=1> 
                <tr> 
                    <td width=150> File name</td> 
                    <td width=100> File Size</td> 
                    <td width=100>Last Modified</td> 
                </tr>"; 
for ($i=0;$i<$i2;$i++) { 
    if (!$do_link) { 
        $line = "<tr><td align=right>" .  
                        $new_array[$i][0] .  
                        "</td><td align=right>" .  
                        number_format(($new_array[$i][1]/1024)) .  
                        "k"; 
        $line = $line  . "</td><td align=right>" . $new_array[$i][3] . "</td></tr>"; 
    }else{ 
        $line = '<tr><td align=right><A HREF="' .   
                        $new_array[$i][0] . '">' .  
                        $new_array[$i][0] .  
                        "</A></td><td align=right>"; 
        $line = $line . number_format(($new_array[$i][1]/1024)) .  
                        "k"  . "</td><td align=right>" .  
                        $new_array[$i][3] . "</td></tr>"; 
    } 
    echo $line; 
} 
echo "</table>"; 


?>
2
répondu solution fix 2013-03-28 09:54:05

j'utilise ce 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");

}
}


?>
2
répondu Zbigniew 2015-10-24 13:58:38

utilisez glob.

glob('*.xml')

pour en savoir plus sur l'utilisation de glob et le filtrage avancé:

http://domexception.blogspot.fi/2013/08/php-using-functional-programming-for.html

1
répondu Otto-Ville Lamminpää 2013-08-04 15:24:01

la réponse la plus simple est de mettre une autre condition '.xml' == strtolower(substr($file, -3)) .

mais je recommande d'utiliser glob à la place.

0
répondu instanceof me 2010-06-17 13:51:56

vous pouvez étendre la classe RecursiveFilterIterator comme ceci:

class ExtensionFilter extends RecursiveFilterIterator
{
  /**
  * Hold the extensions pass to the class constructor 
  */
  protected $extensions;

  /**
   * ExtensionFilter constructor.
   *  
   * @param RecursiveIterator $iterator
   * @param string|array $extensions Extension to filter as an array ['php'] or
   * as string with commas in between 'php, exe, ini'
   */
  public function __construct(RecursiveIterator $iterator, $extensions)
  {
     parent::__construct($iterator);
     $this->extensions = is_array($extensions) ? $extensions :  array_map('trim', explode(',', $extensions));
  }

  public function accept()
  {
      if ($this->hasChildren()) {
         return true;
      }

      return $this->current()->isFile() &&
         in_array(strtolower($this->current()->getExtension()), $this->extensions);
  }

  public function getChildren()
  {
     return new self($this->getInnerIterator()->getChildren(), $this->extensions);
  }

Maintenant vous pouvez instanciate RecursiveDirectoryIterator avec le chemin comme argument comme ceci:

 $iterator = new RecursiveDirectoryIterator('\path\to\dir');
 $iterator = new ExtensionFilter($iterator, 'xml, php, ini');

 foreach($iterator as $file)
 {
   echo $file . '<br />';
 }

les fichiers ne seront listés que dans le dossier courant.



pour obtenir les fichiers dans les sous-répertoires aussi, passez le $ iterator ( ExtensionFIlter Iterator) à RecursiveIteratorIterator as argument:

$iterator = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::SELF_FIRST);

exécutez maintenant la boucle foreach sur cet itérateur. Vous obtiendrez les fichiers avec l'extension spécifiée

Note:-- assurez-vous également d'exécuter L'ExtensionFilter avant RecursiveIteratorIterator, sinon vous obtiendrez tous les fichiers

0
répondu draGon 2017-04-09 09:06:47