0

I have a php page with following code

$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fwrite($ourFileHandle, "Tracy Tanner1\n");
fwrite($ourFileHandle, "Tracy Tanner2\n");
fclose($ourFileHandle);

testFile.txt content look likes

Tracy Tanner1 Tracy Tanner2

But it not comes like

Tracy Tanner1 
Tracy Tanner2

How can i fix it

1
  • 1
    Just ran it fine on linux here, I assume you are on a windows machine? If so, try \r\n instead of \n.
    – Gazler
    Nov 25, 2010 at 19:25

6 Answers 6

8

Try opening it in something that, unlike Notepad, can handle *nix newlines. That, or write \r\n instead.

1
  • 2
    +1 … the real solution is to use an editor that doesn’t suck, not to change the line endings. IMHO Nov 25, 2010 at 19:36
7

@Linto P D: Add in \r --

<?php
$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fwrite($ourFileHandle, "Tracy Tanner1\r\n");
fwrite($ourFileHandle, "Tracy Tanner2\r\n");
fclose($ourFileHandle);
?>
2

I think you specifically need to use \r\n for a new-line character.

2

I would use PHP_EOL when you want a newline. This will ensure application should be cross-platform-compatible.

This should work:

fwrite($ourFileHandle, 'Tracy Tanner1' . PHP_EOL);

2
  • 2
    This will only add the new line character use on the system the script runs. If the script runs on Linux and he tries to open the file on Windows it does not help. Nov 26, 2010 at 0:37
  • @Felix Kling Oh yeah, PHP_EOL is only useful when writing log files (and similar). I don't think I read the question well enough.
    – alex
    Nov 26, 2010 at 1:27
1

Your code does exactly what you described that it should do. So the problem lies entirely in the application interpreting the file. PHP automatically outputs "\r\n" instead of "\n" on Windows, so you probably created the file on a *nix server and then opened it on Windows with an editor that doesn't support "\n" newlines.

"line\n" is the correct way to write a line in PHP, because it respects the default newlines of the current platform. By using "\r\n" you will break the files for Unix platforms, and you might also have issues when you run the script on Windows.

Use an editor that correctly reads the said newlines, or convert the text files when transferring them from *nix to Windows.

0

What about:

fwrite($ourFileHandle, 'Tracy Tanner1'."\n");

Make sure to use single quotation marks for the text and double quotation marks for the \n.

Does it work?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.