Your Location is: Home > Php

PHP append to a new line in a file [duplicate]

From: China View: 1331 Efaz 

Question

This is my code in PHP:

$singles = fopen("singles.txt", "a");
$user_info = $name . "," . $gender . "," . $age . "," . $personality . "," . 
            $favOS . "," . $minAge . "," . $maxAge . PHP_EOL;
fwrite($singles, $user_info);

When I try to append the first time, is it appended to the same line but after that it is going to new line like I want.

enter image description here

As you see, New11 is added to the same line. I want it to be appended to a new line.

Also there is a trailing new line and I don't want an empty line at the end.

Best answer

Just start the string with a newline, instead of finishing it with one. This should solve both issues - your first append will always start a new line, and your last one won't add a blank newline at the end.

$user_info = PHP_EOL . $name . "," . $gender . "," . $age . "," . $personality . "," . 
        $favOS . "," . $minAge . "," . $maxAge;