问题描述
|
假设我有一个目录如下:
ABC
|_ a1.txt
|_ a2.txt
|_ a3.txt
|_ a4.txt
|_ a5.txt
如何使用PHP将这些文件名获取到一个数组中,并限制为特定的文件扩展名并忽略目录?
解决方法
您可以使用glob()函数:
示例01:
<?php
// read all files inside the given directory
// limited to a specific file extension
$files = glob(\"./ABC/*.txt\");
?>
示例02:
<?php
// perform actions for each file found
foreach (glob(\"./ABC/*.txt\") as $filename) {
echo \"$filename size \" . filesize($filename) . \"\\n\";
}
?>
示例03:使用RecursiveIteratorIterator
<?php
foreach(new RecursiveIteratorIterator( new RecursiveDirectoryIterator(\"../\")) as $file) {
if (strtolower(substr($file,-4)) == \".txt\") {
echo $file;
}
}
?>
, 尝试这个:
if ($handle = opendir(\'.\')) {
$files=array();
while (false !== ($file = readdir($handle))) {
if(is_file($file)){
$files[]=$file;
}
}
closedir($handle);
}
, “ 5”列出指定路径内的文件和目录。
, 这是基于本文基准测试的最有效方法:
function getAllFiles() {
$files = array();
$dir = opendir(\'/ABC/\');
while (($currentFile = readdir($dir)) !== false) {
if (endsWith($currentFile,\'.txt\'))
$files[] = $currentFile;
}
closedir($dir);
return $files;
}
function endsWith($haystack,$needle) {
return substr($haystack,-strlen($needle)) == $needle;
}
只需使用getAllFiles()函数,甚至可以对其进行修改以采用文件夹路径和/或所需的扩展名,这很容易。
, 除了scandir(@miku)外,您可能还会发现glob对于通配符匹配很有趣。
, 如果文本文件是文件夹中所有文件的全部,则最简单的方法是使用scandir,如下所示:
<?php
$arr=scandir(\'ABC/\');
?>
如果您还有其他文件,则应按照劳伦斯的答案使用glob。
, $dir = \"your folder url\"; //give only url,it shows all folder data
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != \'.\' and $file != \'..\'){
echo $file .\'<br>\';
}
}
closedir($dh);
}
}
输出:
xyz
abc
2017
motopress