读取特定文件夹中的所有txt文件,并将所有内容写入一个txt文件


Read all txt files in a specific folder and write all contents in one txt file

我尝试从一个文件夹中读取所有*.txt文件,并将每个文件中的所有内容写入另一个txt文件。但不知何故,它只在txt文件中写入一行。

我尝试了fwrite()file_put_contents(),但都不起作用。

这是我的代码:

<?php
    $dh = opendir('/Applications/XAMPP/xamppfiles/htdocs/test/');
    while($file = readdir($dh)) {
        $contents = file_get_contents('/Applications/XAMPP/xamppfiles/htdocs/test/' . $file);
        $dc = array($contents);   
    }
    file_put_contents('content.txt', $dc);
?>

这应该适用于您:

(在这里,我用glob()获取目录中的所有*.txt文件。之后,我用foreach循环遍历每个文件,并用file_get_contents()获取每个文件的内容,然后用file_put_contents()将内容放入目标文件)

<?php
    $files = glob("path/*.txt");
    $output = "result.txt";
    foreach($files as $file) {
        $content = file_get_contents($file);
        file_put_contents($output, $content, FILE_APPEND);
    }
?>

尝试这个

$contents = array();
$line = file(/*next file in dir*/);
foreach($lines as line){
   array_push($line, $contents);
}
//File path of final result
    $filepath = "mergedfiles.txt";
    $out = fopen($filepath, "w");
    //Then cycle through the files reading and writing.
      foreach($filepathsArray as $file){
          $in = fopen($file, "r");
          while ($line = fgets($in)){
                print $file;
               fwrite($out, $line);
          }
          fclose($in);
      }
    //Then clean up
    fclose($out);
    return $filepath;