This is my function for writing a csv file and then downloading it. I have a dropdown menu $_REQUEST['page_start_date'] and $_REQUEST['page_end_date']. In some options file download, in other options it doesn't. The problem is this part always works correct
foreach ( $employees as $employee ) {
fputcsv( $file, $employee );
}
And i write file content on the local server. That's why I don't get it why the file sometimes download and sometimes don't.
function crb_export_employees() {
$start_date = $_REQUEST['page_start_date'];
$end_date = $_REQUEST['page_end_date'];
$employees = crb_get_employees_started_in_date_range( $start_date, $end_date
);
$filePath = CRB_THEME_DIR . 'employees.csv';
$file = fopen( $filePath, 'w+');
foreach ( $employees as $employee ) {
fputcsv( $file, $employee );
}
fclose( $file );
header( 'Cache-Control: public' );
header( "Content-type: application/x-msdownload", true, 200 );
header( 'Content-Disposition: attachment; File Transfer' );
header( 'Content-Disposition: attachment; filename="employees.csv"' );
header( "Pragma: no-cache");
header( "Expires: 0");
readfile( $filePath );
wp_safe_redirect( wp_get_referer() );
exit;
}
I think if the filesize is relatively small a single call to readfile
generally works but if the file is larger then reading the file in chunks is more reliable. The portion of code below is what I have used for a while to force the download of csv files - it reads in small chunks until the eof
marker is reached.
function crb_export_employees() {
$start_date = $_REQUEST['page_start_date'];
$end_date = $_REQUEST['page_end_date'];
$employees = crb_get_employees_started_in_date_range( $start_date, $end_date );
$filepath = CRB_THEME_DIR . 'employees.csv';
$file = fopen( $filepath, 'w+');
foreach ( $employees as $employee ) {
fputcsv( $file, $employee );
}
fclose( $file );
if( !is_file( $filepath ) or connection_status()!=0 ) return FALSE;
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");
header("Content-Type: application/octet-stream");
header("Content-Length: ".(string)( filesize( $filepath ) ) );
header("Content-Disposition: inline; filename=employee.csv");
header("Content-Transfer-Encoding: binary\n");
if( $file = @fopen( $filepath, 'rb' ) ) {
while( !@feof( $file ) and ( connection_status()==0 ) ) {
print( fread( $file, 1024*8 ) );
flush();
}
@fclose( $file );
}
wp_safe_redirect( wp_get_referer() );
return( ( connection_status()==0 ) and !connection_aborted() );
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.