PHPでCSVファイルを出力するためのコードサンプルです。
CsvWriterクラスが本体です。最低限のメソッドを定義してあるだけなので必要に応じて拡張してみてください。
Writerインタフェースを定義して、CsvWriterクラスのコンストラクタに渡して切り替えることで、出力方式を変更することができます。
CsvWriterクラス
CSV形式で出力するための本体のクラスです。このクラスのコンストラクタにWriterインタフェースを実装したクラスを渡します。
<?php
class CsvWriter {
private Writer $writer;
private $elements = [];
public function __construct(Writer $writer)
{
$this->writer = $writer;
}
public function init()
{
$this->writer->init();
}
public function appendValuesBySpecificOrder(array $values, $keys)
{
foreach ($keys as $key)
{
$this->appendEscaped($values[$key] ?? $default);
}
return $this;
}
public function appendValues(array $values)
{
foreach ($values as $value)
{
$this->appendEscaped($value);
}
return $this;
}
public function appendAsLine(array $values)
{
foreach ($values as $value)
{
$this->appendEscaped($value);
}
return $this->newLine();
}
public function appendEscaped($value)
{
$this->elements[] = '"'.strtr('"', '""', $value).'"';
return $this;
}
public function newLine()
{
$this->writer->write(implode(',', $this->elements)."\n");
$this->elements = [];
return $this;
}
public function close()
{
$this->writer->write(implode(',', $this->elements));
$this->writer->close();
}
}
Writerクラス
Writerインタフェースを実装したサンプルクラスです。
<?php
interface Writer {
function init();
function write($value);
function close();
}
<?php
namespace Util\Writer;
// echoして出力 (Webのレスポンスで直接出力する場合は最速)
class EchoWriter implements Writer{
public function init() {}
public function write($value) {
echo $value;
}
public function close() {}
}
<?php
// 文字列生成
class StringWriter implements Writer{
private string $result = '';
public function __construct(&$result) {
$this->result = &$result;
}
public function init() {}
public function write($value) {
$this->result .= $value;
}
public function close() {}
}
<?php
// ファイルへの書き込み
class BufferedStreamFileWriter implements Writer {
private $path;
private $bufferSize = 0;
private $bufferLimit;
private $buffer = '';
public function __construct($path, $bufferLimit, $mode='a') {
$this->path = $path;
$this->bufferLimit = $bufferLimit;
$this->handle = fopen($path, $mode);
}
public function init() {}
public function write($string) {
$size = strlen($string);
$this->bufferSize += $size;
$this->buffer .= $string;
if($this->bufferSize > $this->bufferLimit)
{
$this->flush();
}
}
public function close() {
$this->flush();
fclose($this->handle);
}
public function flush() {
if($this->buffer)
{
fputs($this->handle, $this->buffer);
$this->bufferSize = 0;
$this->buffer = '';
}
}
}
使用例
CsvWriterに、StringWriterを組み合わせた場合の使用例です。
<php
$result = '';
$writer = new CsvWriter(new StringWriter($result));
$writer->init();
$writer->appendAsLine(['a', 'b', 'c'])
->appendAsLine(['e', 'f', 'g']);
echo $result
// 出力結果
// "a","b","c"
// "e","f","g"
// (最後は改行付き)
コメント