Django Johnson
Django Johnson

Reputation: 1449

Combine / merge all files in dir into one text file

I am trying to merge all files in a dir into one text file with PHP.

All the files are text files and have one word on each line.

I just need to combine them all into one text file with all the words, one on each line.

The files extensions are numbers 0-5 multiples of 5 (.10, .15, .20, .25) and .txt files.

This is what I have so far, but it only makes an empty text file.

<?php
$files = glob("./*.??");
$out = fopen("listTogether.txt", "w");
foreach($files as $file){
    $in = fopen($file, "r");
    while($line = fread($in)){
       fwrite($out, $line);
       echo "writing file";
    }
    fclose($in);
}
fclose($out);
?>
<!Doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>file merger</title>
</head>
<body>
    <p>Doo Wop</p>
</body>
 </html>

Upvotes: 3

Views: 5230

Answers (3)

Tadeck
Tadeck

Reputation: 137320

If you can (eg. if you do not need to process the files before concatenation and have appropriate OS), really preferable way is to handle that as close to the OS, as possible:

exec('cat *.?? > listTogether.txt');

If necessary, you can change working directory either within the command itself (by appending "cd /some/other/directory &&", taking into account safe mode limitations regarding paths), or using chdir().

Upvotes: 1

jzer7
jzer7

Reputation: 180

There are 2 issues with your code:

  • The call to fread() requires a parameter indicating maximum number of characters you can read for that file. It is not elegant, but you can set it to something like 20 (if the file is longer, the while loop will execute until all the content is consumed).

    while($line = fread($in,20)){
       fwrite($out, $line);
       echo "writing file";
    }
    
  • This might be a problem or note, but your glob statement says '.??'. So you can capture files like "foo.55", but not "bar.5", or "mine.100". You might want to change it to ".[0-9]*"

    $files = glob("./*.[0-9]*");
    

Upvotes: 2

Jon
Jon

Reputation: 437366

The problem is that the read/append loop doesn't read properly. If you 're not processing very large files then you can just simplify it to

foreach ($files as $file) {
    fwrite($out, file_get_contents($file));
}

Upvotes: 3

Related Questions