LoginSignup
1
2

More than 1 year has passed since last update.

League\CSVでCSV作成

Last updated at Posted at 2021-05-17

League\CSVでCSV作成する方法について

概要

League\CSVでCSV作成する際のモジュールになります。

プログラム

よく利用するBOM付きUTF-8SJIS-winで作成する機能をそれぞれ定義しています。

<?php
namespace App\Services\Common;

use League\Csv\CharsetConverter;
use League\Csv\Writer;

class CsvService
{
    /**
     * BOM付きUTF-8のCSV作成
     *
     * @param string $filePath
     * @param array $records
     * @return string
     */
    public static function createWithUtf8(string $filePath, array $records)
    {
        if (!empty($records[0]) && !empty($records[0][0])) {
            $records[0][0] = "\xEF\xBB\xBF" . $records[0][0];
        }
        $writer = Writer::createFromPath($filePath, 'w+');
        $writer->insertAll($records);
        return $filePath;
    }

    /**
     * SJIS-winのCSV作成
     *
     * @param string $filePath
     * @param array $records
     * @return string
     */
    public static function createWithSjis(string $filePath, array $records)
    {
        $writer = Writer::createFromPath($filePath, 'w+');
        $encoder = (new CharsetConverter())
            ->inputEncoding('utf-8')
            ->outputEncoding('SJIS-win');
        $writer->addFormatter($encoder);
        $writer->insertAll($records);
        return $filePath;
    }
}

解説

ExcelでUTF-8と認識させる方法として、BOM付きUTF-8で保存するために以下を入れています。

if (!empty($records[0]) && !empty($records[0][0])) {
    $records[0][0] = "\xEF\xBB\xBF" . $records[0][0];
}

使い方

以下のような形でファイルパスとcsvの中身を渡せば利用できます。

<?php
namespace App\Services\Csvs;

use App\Services\Common\CsvService;

class TestCsvService
{
    public function create()
    {
        $filePath = '/var/www/html/app/storage/test.csv';
        $records = [
            ['No', '氏名'],
            [1, 'テスト太郎'],
        ];
        return CsvService::createWithUtf8($filePath, $records);
    }
}

参考

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2