• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 61
  • Last Modified:

Combine all files

How can I combine all the files I have in a directory?
I want them to be all copied in a document to be called "combined.txt"
0
Jasmine Ikhreishi
Asked:
Jasmine Ikhreishi
  • 3
1 Solution
 
Dan CraciunIT ConsultantCommented:
cat $(ls -t) > combined.txt

That's a Linux command. Wrap it in PHP and you're set.

HTH,
Dan
0
 
Jasmine IkhreishiAuthor Commented:
Yes but the first one has certain criteria, while this one is any file in the directory
0
 
Julian HansenCommented:
Then just remove the criteria - make it *.*

So for the first sample
<?php
$output = 'combined.txt';
$files = glob("*.*");
unlink($output);
foreach($files as $f) {
    file_put_contents($output, file_get_contents($f), FILE_APPEND);
}

Open in new window

Second option adapted from (Ray's Solution)
$input = 'path/to/input';
$output = 'path/to/combine.txt';
$iterator = new FilesystemIterator($input, FilesystemIterator::SKIP_DOTS + FilesystemIterator::CURRENT_AS_PATHNAME);
unlink($output);
foreach ($iterator as $key => $filepath)
{
    file_put_contents($output, file_get_contents($filepath), FILE_APPEND);
}

Open in new window


EDIT:
The Second solution is about 4x faster than the first.
0
 
Julian HansenCommented:
Corrected code - there were errors in the post above
$iterator = new FilesystemIterator($input, FilesystemIterator::SKIP_DOTS + FilesystemIterator::CURRENT_AS_PATHNAME);
@unlink($output);
foreach ($iterator as $key => $filepath)
{
  file_put_contents($output, file_get_contents($filepath), FILE_APPEND);
}

Open in new window

0
 
Julian HansenCommented:
And in case there are folders in the input directory
$iterator = new FilesystemIterator($input, FilesystemIterator::SKIP_DOTS + FilesystemIterator::CURRENT_AS_PATHNAME);
@unlink($output);
foreach ($iterator as $key => $filepath)
{
  if (!is_dir($filepath)) {
    file_put_contents($output, file_get_contents($filepath), FILE_APPEND);
  }
}

Open in new window

0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now