I want to export data as CSV file. This is my test function
private function exportToCSV()
{
$titles = array('one', 'two', 'three');
$delimiter = ',';
$filename = 'simple.csv';
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename={$filename}");
header("Expires: 0");
header("Pragma: public");
$file = @fopen( 'php://output', 'w' );
fwrite($file, implode($delimiter, $titles) . "\r\n");
fclose($file);
}
I run this function inside a module and I'm getting csv file with titles but whole page as well. How to get only csv file with titles only ?
-
1It would be helpful if you could provide some sample input and the resulting output to demonstrate the problem you're having.Trott– Trott2011年09月03日 08:19:51 +00:00Commented Sep 3, 2011 at 8:19
-
Sorry but i can't understand what mean 'whole page as well'? Please more explaineZigZag– ZigZag2011年09月03日 08:20:05 +00:00Commented Sep 3, 2011 at 8:20
-
What do you mean with "whole page as well"? The rest of the website (are you in a CMS environment?)?. Or do you mean that you only want the download dialog and not showing a new blank page?hbit– hbit2011年09月03日 08:20:26 +00:00Commented Sep 3, 2011 at 8:20
-
Yes this is CMS environment, administration panel. When I run this function I'm getting file with "page" and titles.devsoft– devsoft2011年09月03日 08:23:54 +00:00Commented Sep 3, 2011 at 8:23
-
1why dont you just use php.net/fputcsv?Gordon– Gordon2011年09月03日 08:31:06 +00:00Commented Sep 3, 2011 at 8:31
1 Answer 1
Ensure that you CMS itself is not sending any headers apart from yours using firebug or Chrome or Charles.
If you want to force your browser to show a save dialog then use content type that it cannot parse. Most browsers can parse 'text/csv'. Try using 'application/vnd.ms-excel'. Any app that can open excel can also open csv files so dont worry about what the browser will do.
Some Internet explorers can even open and show excel within it, but if the user did not select to automatically open such files they dont.