merge all files in directory to one text file



PHP Snippet 1:

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

PHP Snippet 2:

  $files = glob("/path/*.*");

PHP Snippet 3:

  $out = fopen("newfile.txt", "w");

PHP Snippet 4:

  foreach($files as $file){
      $in = fopen($file, "r");
      while ($line = fread($in)){
           fwrite($out, $line);
      }
      fclose($in);
  }

PHP Snippet 5:

  fclose($out);

PHP Snippet 6:

<?php
//Name of the directory containing all files to merge
$Dir = "directory";


//Name of the output file
$OutputFile = "filename.txt";


//Scan the files in the directory into an array
$Files = scandir ($Dir);


//Create a stream to the output file
$Open = fopen ($OutputFile, "w"); //Use "w" to start a new output file from zero. If you want to increment an existing file, use "a".


//Loop through the files, read their content into a string variable and write it to the file stream. Then, clean the variable.
foreach ($Files as $k => $v) {
    if ($v != "." AND $v != "..") {
        $Data = file_get_contents ($Dir."/".$v);
        fwrite ($Open, $Data);
    }
    unset ($Data);
}


//Close the file stream
fclose ($Open);
?>

PHP Snippet 7:

/* Directory Name of the files */
$dir = "directory/subDir";
/* Scan the files in the directory */
$files = scandir ($dir);
/* Loop through the files, read content of the files and put then OutFilename.txt */
$outputFile = "OutFilename.txt";
foreach ($files as $file) {
    if ($file !== "." OR $file != "..") {
        file_put_contents ($outputFile, file_get_contents ($dir."/".$file),  FILE_APPEND);
    }
}