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

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

问题描述:

I try to read all *.txt files from a folder and write all content from each file into another txt file. But somehow it only writes one line into the txt file.

I tried with fwrite() and file_put_contents(), neither worked.

Here is my code:

<?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);

?>

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

我尝试使用 fwrite() code>和 file_put_contents() code>,但都没有工作 这是我的代码: p>

 &lt;?php 
 
 $ nh = 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); 
 
?&gt; 
  code>  pre> 
  div>

This should work for you:

(Here I get all *.txt files in a directory with glob(). After this I loop through every file with a foreach loop and get the content of each single file with file_get_contents() and I put the content into the target file with 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);
    }

?>

try this

$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;