Drongo_III Posted July 26, 2012 Share Posted July 26, 2012 Hi Guys I'm getting something really strange. Basically I have two files, one contains a link (to the other) and the other contains php that generates a simple csv. Link php <?php echo "download your file <a href='http://localhost/creatingcsv/download.php'>HERE</a>"; ?> CSV php <?php //sample array $test = array( array('name', 'address'), array('bilbo', 'bagins') ); //Generate headers for csv $implosion = implode(',',$test[0]); //Add new line $implosion .= "\n"; //Generate csv row of data $implosion.= implode(',', $test[1]); //call function to output data download($implosion); function download($implosion){ header("Content-type: text/csv"); header("Content-Disposition: attachment; filename=file.csv"); header("Pragma: no-cache"); header("Expires: 0"); echo $implosion; } ?> Nothing radical there. But in the csv php file if the <?php tag isn't on line one then the csv generates with new lines above the header data - in the actual csv file that is output. So if I go into csv php file and hit return five times, above the <?php tag, I end up with five empty rows before the data in the csv. Can anyone tell me why this is happening? Dongo Quote Link to comment https://forums.phpfreaks.com/topic/266303-new-lines-in-csv-very-odd/ Share on other sites More sharing options...
PFMaBiSmAd Posted July 26, 2012 Share Posted July 26, 2012 Output_buffering is turned on in your php.ini. You either need to turn it off, or insure you don't output anything before the actual data, or you can use ob_end_clean right before you output your actual data. Quote Link to comment https://forums.phpfreaks.com/topic/266303-new-lines-in-csv-very-odd/#findComment-1364694 Share on other sites More sharing options...
Drongo_III Posted July 26, 2012 Author Share Posted July 26, 2012 You're a genius. That worked perfectly. I'd like to understand why that happens though. How do new lines outside of the php tags end up affecting my output? Is it a quirk of using headers to output data? Quote Link to comment https://forums.phpfreaks.com/topic/266303-new-lines-in-csv-very-odd/#findComment-1364698 Share on other sites More sharing options...
scootstah Posted July 27, 2012 Share Posted July 27, 2012 Because with output buffering, PHP basically "holds on to" any output until the end of script execution (or until the output buffering is otherwise ended). It is common practice to omit the closing PHP tag (?>) to prevent any accidental white-space. The closing tag is not required. Quote Link to comment https://forums.phpfreaks.com/topic/266303-new-lines-in-csv-very-odd/#findComment-1364773 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.