Search code examples
phpfwrite

Fwrite - is this executed?


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?!


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.