1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

League/CSVでSJIS-winでCSV出力する

Posted at

CSVファイルをSJISで読み込むほうはよく出るのですが、
出力するほうは意外と誰も書いてなかったので私が書きます。

こうする

document_root/includes/csv.class.php
<?php

//use League\Csv\Reader;
use League\Csv\Writer;
use League\Csv\CharsetConverter;

require dirname(__FILE__) . '/../third_party/league/csv/autoload.php'; // 適宜読み込み先を変更すること。composerとかで読み込んでたら記述いらんかも

class csv
{
  public function __construct()
  {
    //
  }

  /**
   * Export csv as SJIS-win by League/CSV
   *
   * @params string $fileName e.g. "example.csv"
   * @params array $records e.g. [[1, "山田太郎", 80]]
   * @params array $rowHeader [optional] e.g. ["連番", "氏名", "年齢"]
   * @return void
   * @link https://csv.thephpleague.com/9.0/
   */
  public function export($fileName, $records, $rowHeader = [])
  {
    // SJIS-winで出力
    $encoder = (new \League\Csv\CharsetConverter())->inputEncoding('utf-8')->outputEncoding('SJIS-win');

    $csv = \League\Csv\Writer::createFromFileObject(new \SplTempFileObject());

    $csv->addFormatter($encoder);

    // 見出し行
    if(is_array($rowHeader) && count($rowHeader) > 0){
      $csv->insertOne($rowHeader);
    }

    // データ行
    foreach($records as $record){
      $csv->insertOne($record);
    }

    $csv->output($fileName);
    exit;
  }
}
document_root/index.php

require dirname(__FILE__) . '/includes/csv.class.php';

$csv = new csv();

$fileName = "ファイル名.csv";
$rowHeader = ["み","だ","し","行"];
$records = [
  ["な","か","み","1"],
  ["な","か","み","2"],
  ["な","か","み","3"]
];

$csv->export($fileName, $records, $rowHeader);

参考URL

https://csv.thephpleague.com/9.0/converter/charset/
https://qiita.com/kiyc/items/f70280e13e5194e5dd94

1
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?