Skip to content

Instantly share code, notes, and snippets.

@julien1619
Last active January 20, 2016 10:17
Show Gist options
  • Save julien1619/86bf98b5333d1c4a6b59 to your computer and use it in GitHub Desktop.
Save julien1619/86bf98b5333d1c4a6b59 to your computer and use it in GitHub Desktop.
<?php
/**
* WExport.php
*/
defined('WITYCMS_VERSION') or die('Access denied');
// filter class that applies CRLF line endings
class crlf_filter extends php_user_filter
{
function filter($in, $out, &$consumed, $closing)
{
while ($bucket = stream_bucket_make_writeable($in)) {
// make sure the line endings aren't already CRLF
$bucket->data = preg_replace("/(?<!\r)\n/", "\r\n", $bucket->data);
$consumed += $bucket->datalen;
stream_bucket_append($out, $bucket);
}
return PSFS_PASS_ON;
}
}
/**
* WExport helps to export data.
*
* @package System\WCore
* @author Johan Dufau <johan.dufau@creatiwity.net>
* @author Thibault Vlacich <thibault@vlacich.fr>
* @version 0.5.0-dev-02-01-2015
*/
class WExport {
/*
$data = array( // Table
array( // Row
"Column1" => "Row1Value1", // Col
"Column2" => "Row1Value3",
"Column3" => "Row1Value2"
),
array( // Row
"Column1" => "Row1Value1", // Col
"Column2" => "Row1Value3",
"Column3" => "Row1Value2"
)
);
*/
public static function toCSVNamed($filename_prefix, array &$data) {
$filename = $filename_prefix.'_' . date('Ymd-His') . '.csv';
// Disable caching
$now = gmdate('D, d M Y H:i:s');
header('Expires: Tue, 03 Jul 2001 06:00:00 GMT');
header('Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate');
header('Last-Modified: '.$now.' GMT');
// Disposition / encoding on response body
header('Content-Disposition: attachment;filename='.$filename);
header('Content-Transfer-Encoding: binary');
header('Content-Encoding: UTF-8');
header('Content-type: text/csv; charset=UTF-8');
// CRLF filter registration
stream_filter_register('crlf', 'crlf_filter');
$output = fopen('php://output', 'w');
// CRLF enabled
stream_filter_append($output, 'crlf');
if (!empty($data)) {
fwrite($output, "\xEF\xBB\xBF"); // UTF-8 BOM
// Columns name
fputcsv($output, array_keys(reset($data)), ';');
// Values
foreach ($data as $line) {
fputcsv($output, $line, ';');
}
}
fclose($output);
exit();
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment