Search code examples
phpstringfile-iofopenfwrite

php writing to file change the string look


I have a file named "B-small-practice.in" its content is as follow

this is a test
foobar
all your base
class
pony along 

I wrote a code its function is to reverse the words in each line and write them to another file "output.txt" .
here is the code:

$file = fopen("B-small-practice.in", "r");
$lines = array();
while(!feof($file)){
$lines[] = fgets($file); 
}
fclose($file);

$output = fopen("output.txt", "a");

foreach($lines as $v){
    $line = explode(" ", $v);
    $reversed = array_reverse($line);
    $reversed = implode(" ", $reversed);
    fwrite($output, $reversed."\n");
}

fclose($output);
?>

the expected output of the code would to write to the "output.txt" the following:

    test a is this
    foobar
    base your all
    class
    along pony 

But this is what I get:

test  
  a is this
foobar  

base  
 your all  
class

along  
 pony   

what makes it look like that?


Solution

  • the "last" part after exploding still contains the linebreak, so after revertig and imploding, the linebreak is behind the first word. just trim() your string before exploding and add linebreaks ("\n") again when outputting (you already do that).