Tutorial :How to stop PHP prefixing LF to start of file



Question:

I am using PHP to pass some information in a text file back to the user which is then used as input for an app. I'm using the method shown in the following snippet to serve the file to the user.

header('Content-type: text/csv');  header('Content-Disposition: attachment; filename=filename.dat');  echo $data;  exit();  

I get the save as dialogue fine and the data is present the only problem is that there is a line feed character at the start of the output file which I cant seem to get rid of.

It just so happens that the app that uses the data is sensitive to white space and although it would be easy to fix this, forcing the users to update is not a route I want to go down for various reasons.

Does anyone know what is causing this and more importantly any workarounds.


Solution:1

As I already said in the comments to the question:

Either you $data contains that line feed or there is something before that snippet that does this. Maybe a line feed before you opened the PHP block.


Solution:2

Probably $data contains the line feed. Look for includes too


Solution:3

Presumably the extra newline is getting into $data somehow. If you can’t fix that, you could trim() the data before you echo it.

Can you post how you're setting $data?


Solution:4

Just an additional note.

In case you are working on a project where you cannot identify the files that have the leading or trailing line feeds, new lines, carriage returns just call the code below before your headers:

//Loop through any open buffers and nuke them.  while(@ob_end_clean());   header('Content-type: text/csv');  header('Content-Disposition: attachment; filename=filename.dat');  echo $data;  exit();  

This may have some unexpected side-effects on the code that relies on those buffers but is an effective way to completely clear out your output buffer.


Solution:5

Maybe you can use ob_get_contents or ob_get_length to see if anything has been sent to the output before the echo statement. Or use ob_clean before the echo.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »