2012-06-16 37 views
2

我想列出子目录中的文件并将这些列表写入单独的文本文件。php将子目录的内容写入单独的文本文件

我设法获取目录和子目录列表,甚至将所有文件写入文本文件。

我只是似乎没有办法突破我创建的循环。我最终会得到一个单独的文本文件,或者第二个+文件也包含所有先前的子目录内容。

我需要实现的是:

  • DIR A/AA/a1.txt,a2.txt >> AA.log
  • DIR A/BB/b1.txt,b2.txt> > BB.log

希望这是有道理的。

我发现PHP SPL RecursiveDirectoryIterator RecursiveIteratorIterator retrieving the full tree中描述的recursiveDirectoryIterator方法很有帮助。然后我使用一个for和一个foreach循环遍历目录,写入文本文件,但我不能将它们分解成多个文件。

+1

-1。没有PHP代码。 –

+0

我不明白你的问题是什么。我通常会说这样的问题是可以解决的,但是你给的描述留下了太多变量的空间,所以我认为你应该改善你的问题。 – hakre

+0

请提供您遇到问题的源代码。 –

回答

2

很可能你没有筛选出目录...

$maindir=opendir('A'); 
if (!$maindir) die('Cant open directory A'); 
while (true) { 
    $dir=readdir($maindir); 
    if (!$dir) break; 
    if ($dir=='.') continue; 
    if ($dir=='..') continue; 
    if (!is_dir("A/$dir")) continue; 
    $subdir=opendir("A/$dir"); 
    if (!$subdir) continue; 
    $fd=fopen("$dir.log",'wb'); 
    if (!$fd) continue; 
    while (true) { 
    $file=readdir($subdir); 
    if (!$file) break; 
    if (!is_file($file)) continue; 
    fwrite($fd,file_get_contents("A/$dir/$file"); 
    } 
    fclose($fd); 
} 
+0

感谢您的回复至今!我会通过上面的工作和天气解决或不,我会带回源代码。只有我以前没有过的理由,因为我尝试了多重方法,总是失败。我从上面看到的第一件事是,我的想法可能是不正确的,我可能一直在使用错误的循环类型。很快回来,再次感谢! – datafunk

1

我想我会表现出不同的方式,因为这似乎是一个不错的地方使用glob

// Where to start recursing, no trailing slash 
$start_folder = './test'; 
// Where to output files 
$output_folder = $start_folder; 

chdir($start_folder); 

function glob_each_dir ($start_folder, $callback) { 

    $search_pattern = $start_folder . DIRECTORY_SEPARATOR . '*'; 

    // Get just the folders in an array 
    $folders = glob($search_pattern, GLOB_ONLYDIR); 

    // Get just the files: there isn't an ONLYFILES option yet so just diff the 
    // entire folder contents against the previous array of folders 
    $files = array_diff(glob($search_pattern), $folders); 

    // Apply the callback function to the array of files 
    $callback($start_folder, $files); 

    if (!empty($folders)) { 
     // Call this function for every folder found 
     foreach ($folders as $folder) { 
      glob_each_dir($folder, $callback); 
     } 
    } 
} 

glob_each_dir('.', function ($folder_name, Array $filelist) { 
     // Generate a filename from the folder, changing/or \ into _ 
     $output_filename = $_GLOBALS['output_folder'] 
      . trim(strtr(str_replace(__DIR__, '', realpath($folder_name)), DIRECTORY_SEPARATOR, '_'), '_') 
      . '.txt'; 
     file_put_contents($output_filename, implode(PHP_EOL, $filelist)); 
    }); 
+0

嗨,大家回来说谢谢 - 我应该回报(我认为),但这是一个家庭项目,工作完全超过了过去一周的生活,我还没有钉牢它,但尽快回到它!再次感谢您的帮助! – datafunk

相关问题