0

I have written a function to create csv file usin the below code.I am getting Headers already sent warning and I can't able to create the csv file too.How can I fix this problem.I have attached the code here.

function create_csv_file(){
$date = new DateTime();
$ts = $date->format( 'Y-m-d H:i:s' );
$result = array();
$result[] = array(
    "first_name" => "Faison", "last_name" => "Zutavern",
    "product_viewed" => "Sunglasses", "time_viewed" => $ts
);
$result[] = array(
    "first_name" => "Faison", "last_name" => "Zutavern",
    "product_viewed" => "Razor", "time_viewed" => $ts
);
$filename = "report-$ts.csv";
ob_start();
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);
$fp = fopen('php://output', 'w');
$hrow = $result[0];
fputcsv($fp, array_keys($hrow));
foreach ($result as $data) {
    fputcsv($fp, $data);
}
fclose($fp);
}
  • Do you call this function after headers are sent? – fuxia Apr 8 '15 at 4:01
  • yes,Am I doing wrong? – John Apr 8 '15 at 16:17
  • Well, obviously. :) Have you seen this solution? – fuxia Apr 8 '15 at 20:34
  • I am using the create_csv_file in my template page.Will this solution work for me? – John Apr 9 '15 at 3:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.