I need php code example to merge 2 txt files into 1 txt file. Example: Take the contents from file1.txt and merge with the contents of file2.txt file1.txt toy guns|867|6984 rolling stones|1502|12100 black blazer|12|97 laser|1726|13904 boat motor|315|2538 file2.txt 45800000|25800|black paint 403000000|44800|big ball 331000000|2654|gold money 167000000|4432|secret 192000000|53454|planet green Merging the content of both txt files should look like this. merge.txt toy guns|867|6984|45800000|25800|black paint rolling stones|1502|12100|403000000|44800|big ball black blazer|12|97|331000000|2654|gold money laser|1726|13904|167000000|4432|secret boat motor|315|2538|192000000|53454|planet green
Try this: $content= array(); $fp = fopen( 'file1.txt', 'r' ); while( !feof($fp) ) { $buffer = fgets($fp,4096); $content[] = $buffer; } fclose($fp); $content2= array(); $fp = fopen( 'file2.txt', 'r' ); while( !feof($fp) ) { $buffer = fgets($fp,4096); $content2[] = $buffer; } fclose($fp); $fp= fopen('merge.txt','w'); fclose($fp); $fp= fopen('merge.txt','a'); foreach($content as $k=>$kk){ $a= $content[$k]. "|". $content2[$k]."\r\n"; fwrite($fp,$a); } fclose($fp);
I was looking for something similar myself. Can you explain why you need the line '$fp= fopen('merge.txt','w'); fclose($fp);' as it seems to just open and close a file without doing anything.
I worked but has a bug. When using JEET's code to merged the 2 txt files it merged like this. Only the last line was formated correctly toy guns|867|6984 |45800000|25800|black paint rolling stones|1502|12100 |403000000|44800|big ball black blazer|12|97 |331000000|2654|gold money laser|1726|13904 |167000000|4432|secret boat motor|315|2538|192000000|53454|planet green
I found another way of merging 2 txt files line by line into 1 txt file <?php $a = file('file1.txt'); $b = file('file2.txt'); $c = array(); foreach($a as $k=>$v) $c[]= trim($v).'|'.trim($b[$k]); $fp = fopen('merge.txt', 'w+'); fwrite($fp, join("\r\n", $c)); fclose($fp); ?> PHP: