php 目录中每个文件的循环代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6155533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loop code for each file in a directory
提问by Chiggins
I have a directory of pictures that I want to loop through and do some file calculations on. It might just be lack of sleep, but how would I use PHP to look in a given directory, and loop through each file using some sort of for loop?
我有一个图片目录,我想遍历它并对其进行一些文件计算。可能只是睡眠不足,但我将如何使用 PHP 查看给定目录,并使用某种 for 循环遍历每个文件?
Thanks!
谢谢!
回答by Emil Vikstr?m
回答by squirrel
Check out the DirectoryIteratorclass.
From one of the comments on that page:
从该页面上的评论之一:
// output all files and directories except for '.' and '..'
foreach (new DirectoryIterator('../moodle') as $fileInfo) {
if($fileInfo->isDot()) continue;
echo $fileInfo->getFilename() . "<br>\n";
}
The recursive version is RecursiveDirectoryIterator.
回答by fvox
回答by Phill Pafford
回答by Jake
Use the glob function in a foreach loop to do whatever is an option. I also used the file_exists function in the example below to check if the directory exists before going any further.
在 foreach 循环中使用 glob 函数来执行任何选项。我还在下面的示例中使用了 file_exists 函数来检查目录是否存在,然后再继续。
$directory = 'my_directory/';
$extension = '.txt';
if ( file_exists($directory) ) {
foreach ( glob($directory . '*' . $extension) as $file ) {
echo $file;
}
}
else {
echo 'directory ' . $directory . ' doesn\'t exist!';
}