Help us understand the problem. What is going on with this article?

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

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

qwe001
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした