Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 900
Django Johnson Avatar asked Dec 14 '25 05:12

Django Johnson


1 Answers

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));
}
like image 70
Jon Avatar answered Dec 15 '25 18:12

Jon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!