Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate files in PHP

Tags:

php

I'd like to know if there is a faster way of concatenating 2 text files in PHP, than the usual way of opening txt1 in a+, reading txt2 line by line and copying each line to txt1.

like image 443
JorgeeFG Avatar asked Jul 01 '13 15:07

JorgeeFG


3 Answers

If you want to use a pure-PHP solution, you could use file_get_contents to read the whole file in a string and then write that out (no error checking, just to show how you could do it):

$fp1 = fopen("txt1", 'a+');
$file2 = file_get_contents("txt2");
fwrite($fp1, $file2);
like image 90
Bart Friederichs Avatar answered Nov 01 '22 01:11

Bart Friederichs


It's probably much faster to use the cat program in linux if you have command line permissions for PHP

system('cat txt1 txt2 > txt3');
like image 14
Patrick Avatar answered Nov 01 '22 01:11

Patrick


$content = file_get_contents("file1");
file_put_contents("file2", $content, FILE_APPEND);
like image 9
Blackfire Avatar answered Nov 01 '22 02:11

Blackfire