/** * Saves CSV directly in the browser. * * @see https://wpcodebook.com/php-save-csv-directly-browser/ * @see https://www.php.net/manual/en/function.header.php */ function wpcodebook_save_csv_in_browser( $csv, $filename = 'output.csv' ) { // Headers header( 'Content-Description: File Transfer' ); header( 'Content-Type: application/octet-stream' ); header( 'Content-Disposition: attachment; filename=' . $filename ); header( 'Content-Transfer-Encoding: binary' ); header( 'Expires: 0' ); header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' ); header( 'Pragma: public' ); header( 'Content-Length: ' . strlen( $csv ) ); // Content echo $csv; // Exit die(); }
Example:
// Data (array) $head = array( 'Name', 'Height', 'Weight' ); $data = array( array( 'Leia', '150', '49' ), array( 'Luke', '172', '77' ), array( 'Han', '180', '80' ), ); array_unshift( $data, $head ); // Convert array to csv $sep = ','; foreach ( $data as &$row ) { $row = implode( $sep, $row ); } $csv = implode( PHP_EOL, $data ); // Save CSV in browser wpcodebook_save_csv_in_browser( $csv );