Created
January 24, 2019 07:31
-
-
Save agronom81/ce114b3cc83c27d42e17a02990ff9824 to your computer and use it in GitHub Desktop.
create and load csv
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* load csv | |
*/ | |
add_action("init", "download_csv"); | |
function download_csv() { | |
if (isset($_POST['download_csv'])) { | |
function outputCsv( $fileName, $assocDataArray ) { | |
ob_clean(); | |
header( 'Pragma: public' ); | |
header( 'Expires: 0' ); | |
header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' ); | |
header( 'Cache-Control: private', false ); | |
header( 'Content-Type: text/csv' ); | |
header( 'Content-Disposition: attachment;filename=' . $fileName ); | |
if ( isset( $assocDataArray['0'] ) ) { | |
$fp = fopen( 'php://output', 'w' ); | |
fputcsv( $fp, array_keys( $assocDataArray['0'] ) ); | |
foreach ( $assocDataArray AS $values ) { | |
fputcsv( $fp, $values ); | |
} | |
fclose( $fp ); | |
} | |
ob_flush(); | |
} | |
$data = array( | |
array( | |
'name' => 'some name', | |
'email' => 'some email' | |
) | |
) | |
$fileName = 'file.csv'; | |
outputCsv( $fileName, $data ); | |
exit; // This is really important - otherwise it shoves all of your page code into the download | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment