I am trying to export results to a csv file using the following code. The export appears to work, but when I open the file, it contains the html code from the page. Any help is appreciated.
ob_start();
global $wpdb;
$domain = $_SERVER['SERVER_NAME'];
$table = $wpdb->prefix . "qi_project_requests";
$filename = "export.csv";
$sql = $wpdb->get_results("select * from $table");
$header_row = array(
'Date Submitted',
'Requestor Name'
);
$data_rows = array();
foreach ($sql as $data) {
$row = array(
$data->date,
$data->rname
);
$data_rows[] = $row;
}
$fh = @fopen( 'php://output', 'w' );
fprintf( $fh, chr(0xEF) . chr(0xBB) . chr(0xBF) );
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' );
fputcsv( $fh, $header_row );
foreach ( $data_rows as $data_row ) {
fputcsv( $fh, $data_row );
}
fclose( $fh );
ob_end_flush();
die();