PHP. Writing to the file

Hi,

I write to the file:


<?php
    $handle = fopen('names.txt', 'w');
    fwrite($handle, 'Ivan'."\
");
    fwrite($handle, 'Billy'."\
");
    fclose($handle);
?>

I expect to see:

Ivan
Billy

But I see:


IvanBilly

P.S. When I copied to this forum from file I saw:

Ivan
Billy

Thank you.

I don’t understand. This code works correctly:


<?php
$filename = 'names.txt';

if (isset($_POST['name'])) {
    $name = $_POST['name'];
    if (!empty($name)) {
        $handle = fopen($filename, 'a');
        fwrite($handle, $name."\
");
        fclose($handle);

        echo 'Current names in file: ';

        $count = 0;
        $readin = file($filename);
        $readin_count = count($readin);
        foreach ($readin as $fname) {
            echo trim($fname);
            if ($count < $readin_count-1) {
                echo ', ';
            }
            $count++;
        }
    }
}
?>

<form action="file.php" method="POST">
    <input type="text" name="name" />
    <br />
    <input type="submit" name="submit" value="Append" />
</form>

But in the file I see:

IvanMaxDanPeterIvan

When I open the file names.txt in the browser I see:

Ivan
Max
Dan
Peter
Ivan

Try

\\r\

This might also be an option but \r
will probably do the job in your case.

PHP_EOL

Thank you very much :slight_smile:

<?php
$handle = fopen(‘names.txt’, ‘w’);
fwrite($handle, "Ivan
");
fwrite($handle, "Billy
");
fclose($handle);
?>
can you try this code.

That will produce the same scenario that he previously had. The issue because the EOL (end of line) character used. Which varies by operating system. Windows, Mac, and Linux all use different EOL. It is usually safe to use \r
, and you can use PHP_EOL if you do not need to transfer your file between different operating systems (otherwise the PHP_EOL will be different on each system, so it might not read back the same).

Guys, for most file I/O scenarios [fphp]file_get_contents[/fphp] and [fphp]file_put_contents[/fphp] will do the job. [fphp]fopen[/fphp] and the related functions used to be the only way to do this sort of things, these days they really are just for situations where the size of the file makes loading it into memory impractical.