PHP whitespace issues when exporting to csv files

Exporting data to a simple CSV file has provided me an array of problems.

The problem:  In every exported .csv file the first row of the document was blank and then the data started in the second row.  The methods I used were: fopen, fputcsv, fclose to put the data into a csv file and setHTTPHeader with renderText and file_get_contents  to export the file for a download.  I tried testing if the loop index was off and was creating the problem but it was not the case.  I also tried making sure I was not inserting any newline characters to the csv file.

The solution:  After trying to debug every step, I have realized that the problem was caused by having an extra two lines at the end of the php file in which the download was called.  After doing more testing, I realized that it only worked for me if there was a blank line and then the ending ?> for my program to work.  Make sure there is a blank line before your PHP end tag and also make sure there are no blank lines after it.

This entry was posted in PHP. Bookmark the permalink.

2 Responses to PHP whitespace issues when exporting to csv files

  1. Peggy Knight says:

    Thank you. In a thousand years, I do not think I could have found that solution. Bless you for posting it!

  2. Donald says:

    an array of problems What a punny choice of words.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>