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.