Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

\n not working in my fwrite()

Not sure what could be the problem.

I'm dumping data from an array $theArray into theFile.txt, each array item on a separate line.

$file = fopen("theFile.txt", "w");
foreach ($theArray as $arrayItem){
    fwrite($file, $arrayItem . '\n');
}
fclose($file);

Problem is when I open theFile.txt, I see the \n being outputted literally. Also if I try to programmatically read the file line by line (just in case lines are there), it shows them as 1 line meaning \n are really not having their desired effect.

like image 845
brett Avatar asked Mar 28 '10 04:03

brett


People also ask

Does fwrite add new line?

When writing to a file in PHP with fwrite , you can add a newline character with PHP_EOL. Using PHP_EOL instead of manually writing out a "\n" or "\r\n" is important to make your code as portable as possible.

Why is fwrite not working in C?

C function fwrite() doesn't write in file Is sizeof(data) == 1 , because if fwrite is returning 1 , then that's all that is being written each time. Yes, I called fclose.

Is fwrite blocking?

Technically fwrite() is a blocking call in that it does not return until the procedure has completed. However the definition of completion for fwrite() is that the data you supply has been written to an internal file buffer.

How do I use fwrite in PHP?

PHP fwrite() Function$file = fopen("test. txt","w"); echo fwrite($file,"Hello World. Testing!");


1 Answers

Enclose \n in double quotes as "\n"

Inside a single quote a \n is treated as a literal slash followed by an n, but inside a double quote it is interpreted as a newline char.

like image 88
codaddict Avatar answered Sep 18 '22 12:09

codaddict