Blake Stone Blake Stone - 2 months ago 11
PHP Question

PHP: How to get proper output into file after merging every line from three or more files?

I'm trying to merge all the lines from three or more files. Each line must be merged with every single line from these files. Each file could have any amount of lines.

Content of files is like this:

file1.txt:
file1 line1
file1 line2
file2.txt:
file2 line1
file2 line2
file3.txt:
file3 line1
file3 line2


As a PHP newbie I've wrote such a code:

<?php
$file1 = file("file1.txt");
$file2 = file("file2.txt");
$file3 = file("file3.txt");
$file777 = fopen("file777.txt", "w");
for($f1=0;$f1<count($file1);$f1++)
for($f2=0;$f2<count($file2);$f2++)
for($f3=0;$f3<count($file3);$f3++)
fwrite($file777, "$file1[$f1] $file2[$f2] $file3[$f3]");
fclose($file777);
?>


But in the result file I'm getting a mess like this:

file1 line1
file2 line1
file3 line1
file1 line1
file2 line1
file3 line2file1 line1
file2 line2 file3 line1
file1 line1
file2 line2 file3 line2file1 line2 file2 line1
file3 line1
file1 line2 file2 line1
file3 line2file1 line2 file2 line2 file3 line1
file1 line2 file2 line2 file3 line2


Instead of a needed result like this:

file1 line1 file2 line1 file3 line1
file1 line1 file2 line1 file3 line2
file1 line1 file2 line2 file3 line1
file1 line1 file2 line2 file3 line2
file1 line2 file2 line1 file3 line1
file1 line2 file2 line1 file3 line2
file1 line2 file2 line2 file3 line1
file1 line2 file2 line2 file3 line2


Could you help me to get a proper output please?

Thanks in advance!

Answer

You're not removing the newlines at the end of each line.

From the php.net manual for file()

Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, file() returns FALSE.

Use trim to remove the newlines.

<?php
$file1 = file("file1.txt");
$file2 = file("file2.txt");
$file3 = file("file3.txt");
$file777 = fopen("file777.txt", "w");
for($f1=0;$f1<count($file1);$f1++)
    for($f2=0;$f2<count($file2);$f2++)
        for($f3=0;$f3<count($file3);$f3++)
            fwrite($file777, trim($file1[$f1]) ." ". trim($file2[$f2] ) ." ".  trim($file3[$f3]) .PHP_EOL );
fclose($file777);
?>
Comments