php PHP如何读取子目录和循环文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2014474/
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
PHP read sub-directories and loop through files how to?
提问by M.E
I need to create a loop through all files in subdirectories. Can you please help me struct my code like this:
我需要在子目录中的所有文件中创建一个循环。你能帮我像这样构造我的代码吗:
$main = "MainDirectory";
loop through sub-directories {
loop through filels in each sub-directory {
do something with each file
}
};
回答by Micha? Rudnicki
Use RecursiveDirectoryIteratorin conjunction with RecursiveIteratorIterator.
将RecursiveDirectoryIterator与 RecursiveIteratorIterator 结合使用。
$di = new RecursiveDirectoryIterator('path/to/directory');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';
}
回答by GSto
You probably want to use a recursive function for this, in case your sub directories have sub-sub directories
您可能想为此使用递归函数,以防您的子目录有子子目录
$main = "MainDirectory";
function readDirs($main){
$dirHandle = opendir($main);
while($file = readdir($dirHandle)){
if(is_dir($main . $file) && $file != '.' && $file != '..'){
readDirs($file);
}
else{
//do stuff
}
}
}
didn't test the code, but this should be close to what you want.
没有测试代码,但这应该接近你想要的。
回答by John Marty
You need to add the path to your recursive call.
您需要将路径添加到递归调用中。
function readDirs($path){
$dirHandle = opendir($path);
while($item = readdir($dirHandle)) {
$newPath = $path."/".$item;
if(is_dir($newPath) && $item != '.' && $item != '..') {
echo "Found Folder $newPath<br>";
readDirs($newPath);
}
else{
echo ' Found File or .-dir '.$item.'<br>';
}
}
}
$path = "/";
echo "$path<br>";
readDirs($path);
回答by Fedir RYKHTIK
I like globwith it's wildcards :
我喜欢glob它的通配符:
foreach (glob("*/*.txt") as $filename) {
echo "$filename\n";
}
Details and more complex scenarios.
But if You have a complex folders structure RecursiveDirectoryIteratoris definitively the solution.
但是,如果您有一个复杂的文件夹结构RecursiveDirectoryIterator,那么绝对是解决方案。
回答by psaniko
Come on, first try it yourself!
来吧,先自己试试吧!
What you'll need:
你需要什么:
scandir()
is_dir()
and of course foreach
而且当然 foreach
http://php.net/manual/en/function.is-dir.php
http://php.net/manual/en/function.is-dir.php
回答by T.Todua
Another solutionto read with sub-directories and sub-files (set correct foldername):
使用子目录和子文件读取的另一种解决方案(设置正确的文件夹名称):
<?php
$path = realpath('samplefolder/yorfolder');
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $filename)
{
echo "$filename <br/>";
}
?>
回答by Santosh
<?php
ini_set('max_execution_time', 300); // increase the execution time of the file (in case the number of files or file size is more).
class renameNewFile {
static function copyToNewFolder() { // copies the file from one location to another.
$main = 'C:\xampp\htdocs\practice\demo'; // Source folder (inside this folder subfolders and inside each subfolder files are present.)
$main1 = 'C:\xampp\htdocs\practice\demomainfolder'; // Destination Folder
$dirHandle = opendir($main); // Open the source folder
while ($file = readdir($dirHandle)) { // Read what's there inside the source folder
if (basename($file) != '.' && basename($file) != '..') { // Ignore if the folder name is '.' or '..'
$folderhandle = opendir($main . '\' . $file); // Open the Sub Folders inside the Main Folder
while ($text = readdir($folderhandle)) {
if (basename($text) != '.' && basename($text) != '..') { // Ignore if the folder name is '.' or '..'
$filepath = $main . '\' . $file . '\' . $text;
if (!copy($filepath, $main1 . '\' . $text)) // Copy the files present inside the subfolders to destination folder
echo "Copy failed";
else {
$fh = fopen($main1 . '\' . 'log.txt', 'a'); // Write a log file to show the details of files copied.
$text1 = str_replace(' ', '_', $text);
$data = $file . ',' . strtolower($text1) . "\r\n";
fwrite($fh, $data);
echo $text . " is copied <br>";
}
}
}
}
}
}
static function renameNewFileInFolder() { //Renames the files into desired name
$main1 = 'C:\xampp\htdocs\practice\demomainfolder';
$dirHandle = opendir($main1);
while ($file = readdir($dirHandle)) {
if (basename($file) != '.' && basename($file) != '..') {
$filepath = $main1 . '\' . $file;
$text1 = strtolower($filepath);
rename($filepath, $text1);
$text2 = str_replace(' ', '_', $text1);
if (rename($filepath, $text2))
echo $filepath . " is renamed to " . $text2 . '<br/>';
}
}
}
}
renameNewFile::copyToNewFolder();
renameNewFile::renameNewFileInFolder();
?>
回答by Ibrahim W.
$allFiles = [];
public function dirIterator($dirName)
{
$whatsInsideDir = scandir($dirName);
foreach ($whatsInsideDir as $fileOrDir) {
if (is_dir($fileOrDir)) {
dirIterator($fileOrDir);
}
$allFiles.push($fileOrDir);
}
return $allFiles;
}
回答by coyotepoint
Minor modification on what John Marty posted, if we can safely eliminate any items that are named . or ..
如果我们可以安全地消除任何名为 . 或者 ..
function readDirs($path){
$dirHandle = opendir($path);
while($item = readdir($dirHandle)) {
$newPath = $path."/".$item;
if (($item == '.') || ($item == '..')) {
continue;
}
if (is_dir($newPath)) {
pretty_echo('Found Folder '.$newPath);
readDirs($newPath);
} else {
pretty_echo('Found File: '.$item);
}
}
}
function pretty_echo($text = '')
{
echo $text;
if (PHP_OS == 'Linux') {
echo "\r\n";
}
else {
echo "</br>";
}
}

