Reputation: 35
I am generating CSV file using PHP. What i am doing is
<?php
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename="myfile.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo "mycontent";
exit;
It generates the CSV file with my content, but two extra spaces (tab spaces, i guess) are being added in the start of CSV content. I have used trim(), and other related functions to remove spaces, but it does not help.
Sample output (with spaces):
first_column,second_column
first_data,second_data
but it should be:
first_column,second_column
first_data,second_data
Please help me how to remove these two extra spaces in the start of CSV file.
Upvotes: 3
Views: 2983
Reputation: 121
I had this exact same problem and finally found a solution after many hours of searching. Adding: ob_end_clean() after the header fixed it...
header('Content-Disposition: attachment; filename="sample.txt"');
ob_end_clean();
I had never used ob_end_clean() before but looks like it cleans up buffers and other things that seem to lead to a double whitespace at the beginning of files created for download in this way. I only found the solution as it was part of the code in a sample not related to this problem so hopefully someone in the future will stumble across this post, fix the problem and move on with their life!
Upvotes: 12