Johner
Johner

Reputation: 25

Open file and write to other file

I need files and write their content to other file. Any ideas how to do it?

I tried the following, but it's not working, the output was only from 1 file not from all

$files = glob('texts/*.txt', GLOB_BRACE);
foreach($files as $file){
  $opn = fopen($file, "r");
  $rad = fread($opn, 1024000);
  fclose($opn);
  $opn = fopen('output.txt', 'a');
  fwrite($opn, $rad);
  fclose($opn);
}

Upvotes: 2

Views: 84

Answers (5)

Johner
Johner

Reputation: 25

I solved the problem:

$filesss = fopen('output.txt', 'a');
if ($handle = opendir('./texts/')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            $obsah = file_get_contents('./texts/'.$entry);
            fwrite($filesss, $entry.$obsah.'
');
        }
    }
    closedir($handle);
}
fclose($filesss);

Not be best solution, but for me just. Thansk :)

Upvotes: 0

Javad
Javad

Reputation: 4397

You can get content of the file by using file_get_contents() and save the content in another file by using file_put_contents()
So you can put below in your loop

$files = glob('texts/*.txt', GLOB_BRACE);
foreach($files as $file){
   // Open the file to get existing content
   $content = file_get_contents($file);
   // Write the contents to the new file
   file_put_contents('new_'.$file, $content);
}

If you want to merge all files content and put them in one file, you can change it as

$files = glob('texts/*.txt', GLOB_BRACE);
$content = ''
foreach($files as $file){
   // Open the file to get existing content
   $content. = file_get_contents($file);
}
// Write the contents to the new file
file_put_contents('output.txt', $content);

Upvotes: 1

Aziz Saleh
Aziz Saleh

Reputation: 2707

If you have execution privileges, this can be faster (If you are on Linux):

$files = glob('texts/*.txt', GLOB_BRACE);
foreach($files as $file){
    exec("cat $file >> output.txt");
}

Without the loop:

exec("cat texts/*.txt >> output.txt");

Upvotes: 0

clami219
clami219

Reputation: 3038

I'm not too sure about that (and it would be interesting to know if you get errors in this regard) but it is possible that the release time of the output file is not fast enough to allow you to reopen it from the second iteration on...

Try with something like this and see if it works:

$files = glob('texts/*.txt', GLOB_BRACE);
$output = fopen('output.txt', 'a');
foreach($files as $file){
    $opn = fopen($file, "r");
    $rad = fread($opn, 1024000);
    fclose($opn);
    fwrite($output, $rad);
}
fclose($output);

Upvotes: 0

Rachel Gallen
Rachel Gallen

Reputation: 28553

If you're using php5 or up use File_put_contents and loop it

e.g.

 int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )

Upvotes: 0

Related Questions