Skip to content

Instantly share code, notes, and snippets.

@m8rge
Last active December 15, 2018 20:49
Show Gist options
  • Save m8rge/7073765314a83980adce728126f6280f to your computer and use it in GitHub Desktop.
Save m8rge/7073765314a83980adce728126f6280f to your computer and use it in GitHub Desktop.
Blazing fast php excel writer. With Yii2 formatter dependency
<?php
/**
* require Yii2 for decimal formatter
*/
class ExcelCsvWriter
{
/**
* @var resource
*/
private $resultStream;
public function __construct($stream)
{
$meta = stream_get_meta_data($stream);
if ($meta['mode'] === 'r') {
throw new \Exception('Can\'t write to read-only stream');
}
$this->resultStream = $stream;
fwrite($this->resultStream, pack('C*', 0xFF, 0xFE)); // UTF16-LE BOM
stream_filter_append($this->resultStream, 'convert.iconv.UTF-8/UTF-16LE', STREAM_FILTER_WRITE);
}
/**
* @param array $row
*/
public function writeRow($row)
{
array_walk($row, function(&$value) {
if (is_float($value)) {
$value = \Yii::$app->formatter->asDecimal($value);
}
});
fputcsv($this->resultStream, $row, "\t", '"');
}
}
<?php
$csvStream = fopen('php://memory', 'w+');
$writer = new ExcelCsvWriter($csvStream);
$writer->writeRow(['a', 3.14, 'b']);
echo stream_get_contents($csvStream);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment