Skip to content

Instantly share code, notes, and snippets.

@maxkostinevich
Created April 12, 2016 09:32
Show Gist options
  • Save maxkostinevich/c7d1a3edf0c992dbfed9edada1c65527 to your computer and use it in GitHub Desktop.
Save maxkostinevich/c7d1a3edf0c992dbfed9edada1c65527 to your computer and use it in GitHub Desktop.
PHP CSV Export
<?php
/**
* Basic CSV Export
*
* (c) 2016 Max Kostinevich - All rights reserved
* https://maxkostinevich.com
*/
// Do some security check here
$domain = $_SERVER['SERVER_NAME'];
header('Content-type: application/x-unknown');
header('Content-Disposition: embed; filename="file-' . $domain . '-' . time() . '.csv"'); // filename
$add_character = "\015\012";
// Grab your data from database or file
$csv_data = array(
'12/04/2016 : [email protected]',
'12/04/2016 : [email protected]',
'12/04/2016 : [email protected]'
); // just for example
$data_count = count( $csv_data );
// CSV Header
$file = "\"Date\",\"Email\"";
$file .= $add_character;
// Add rows to CSV file
if ( $data_count > 0 ) {
foreach( $csv_data as $record ){
list( $date, $email ) = explode( ':', $record );
$file .= "\"" . str_replace( "\"","\"\"", preg_replace( "/\015(\012)?/", "\012", stripslashes( $date ) ) ) . "\",";
$file .= "\"" . str_replace( "\"","\"\"", preg_replace( "/\015(\012)?/", "\012", stripslashes( $email ) ) ) . "\"";
$file .= $add_character;
}
}
echo $file;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment