Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

merge all files in directory to one text file

Tags:

file

php

In PHP, how can I open everyfile, all text files, in a directory and merge them all into one text file.

I don't know how to open all files in a directory, but I would use the file() command to open the next file and then a foreach to append each line to an array. like so:

$contents = array();
$line = file(/*next file in dir*/);
foreach($lines as line){
   array_push($line, $contents);
}

Then I would write that array to a new text file one I've reached no more files in the directory.

if you have a better way of doing this then please let me know.

Or if you can help me implement my solution especially the opening the next file in the dir, please let me know!

like image 653
Django Johnson Avatar asked Jun 06 '13 21:06

Django Johnson


2 Answers

OrangePill's answer is WRONG.

It returns an empty file and a compile ERROR. The problem was that he used fread (reads bytes) instead of fget (reads lines)

This is the working answer:

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

Enjoy!

like image 100
Rod Avatar answered Nov 15 '22 16:11

Rod


The way that you are doing it is going to consume a lot of memory because it has to hold the contents of all of the files in memory ... this approach may be a little better

First off get all of the files you are going to want

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

Then open an output file handle

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

Then cycle through the files reading and writing.

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

Then clean up

  fclose($out);
like image 35
Orangepill Avatar answered Nov 15 '22 17:11

Orangepill