Question

I have a bunch of fwrites that write to a text file. However, its seem that the new line ("\n") that I want after each row never gets put in since the next set of data is stuck to the last line that this code inserts into the text file:

while(odbc_fetch_row($result)){

        if($counter==0){

            $counter3 = 1;

            foreach($column_names as $column_names2){

                if($length!=$counter3){

                    fwrite($write_file, '"'.$column_names2.'",');

                }else{

                    fwrite($write_file, '"'.$column_names2.'"');

                }

                $counter3++;

            }

            //echo 'Never gets executed???';
            fwrite($write_file, "\n");

            $counter = 1;

        }

Any ideas on whats going on?

I have put in "\n\n" as a quick test. What is strange is if I view in this in notepad it is still stuck together, but if I view it in wordpad it shows a line break?!

Was it helpful?

Solution

As others have suggested, it is likely due to the way newlines are encoded on your OS.

However, rather than explicitly output a Windows-specific "\r\n", I suggest that you try opening the file in text (rather than binary) mode. The advantage of opening in text mode is that the system will convert the line endings to whatever format is appropriate for that OS. That way, your code should be more portable, and should (hopefully) work properly on Windows/Linux/Mac etc.

Assuming you are using PHP, you can pass the "text mode translation flag" ('t') into fopen.

OTHER TIPS

The code looks o.k.

Can it be that you are lookign at the file with a Windows application that can't handle \n line breaks? What happens if you substitute the \n by something else?

It's not a problem with your code, but a problem with your viewer. Changing viewers will solve your problem. Changing line terminators to something your viewer understands (\r\n) will also solve the problem. The important thing is to write the line terminator in a way that the program that will later be consuming it will understand. If it's just the viewer, then change the line terminator. If its another program that expects just a newline character, change viewers.

Read this about newlines on various OS.

Windows indicates a new line by using CR + LF (i.e. \r\n) while UNIX(-like) systems only use LF (\n).

CR = Carriage return
LF = Line feed

So you probably have to use \r\n. But other programs like Wordpad seem to understand \n-only too.


The best way is, you use the PHP constant PHP_EOL which uses the end-of-line indicator of the current OS, the script is running:

fwrite($write_file, PHP_EOL);

you can try using \r\n

Try using CRLF line endings:

"\r\n"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top