Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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