Skip to content

Instantly share code, notes, and snippets.

@raiden808
Created July 30, 2018 04:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raiden808/b35b3d53e99b423cd4ddea3461a2dc9c to your computer and use it in GitHub Desktop.
Save raiden808/b35b3d53e99b423cd4ddea3461a2dc9c to your computer and use it in GitHub Desktop.
function export_to_csv(){
//will trigger when export_test isset as get variable
if(isset($_GET['export_test'])){
$file_name = 'csv_file'."_".date("Y-m-d").'.csv';
header('Content-Type: application/csv');
header("Content-Disposition: attachment; filename=".$file_name."");
header('Pragma: no-cache');
header("Expires: 0");
// create a file pointer connected to the output stream
$file = fopen('php://output', 'w');
// send the column headers
fputcsv($file, array('Column 1', 'Column 2', 'Column 3', 'Column 4', 'Column 5'));
// Sample data. This can be fetched from mysql too
$data = array(
array('Data 11', 'Data 12', 'Data 13', 'Data 14', 'Data 15'),
array('Data 21', 'Data 22', 'Data 23', 'Data 24', 'Data 25'),
array('Data 31', 'Data 32', 'Data 33', 'Data 34', 'Data 35'),
array('Data 41', 'Data 42', 'Data 43', 'Data 44', 'Data 45'),
array('Data 51', 'Data 52', 'Data 53', 'Data 54', 'Data 55')
);
// output each row of the data
foreach ($data as $row)
{
fputcsv($file, $row);
}
exit;
}
}
//be sure to hook it to wp not wp_head
add_action('wp','export_to_csv');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment