0
0

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.

PHPでWindows向けのCSVデータをLinuxサーバにて生成する。

Posted at

手間だった為、関数を用意しておく。

生成するCSVデータ

  • 文字コード = Shift-JIS
  • 改行コード = ¥r¥n
    • ¥r = キャリッジ・リターン(carriage return、復帰)
    • ¥n = ライン・フィード(line feed、改行)
  • 項目を囲む文字 = 「"」(ダブルコーテーション)

関数

/**
 * 二次元配列からWindows向けのCSVデータを生成する。
 *
 * @param array $records
 * @param string $delimiter
 * @param string $enclosure
 * @param string $enclosure_escape
 * @param string $line_break
 * @param string $from_encoding
 * @param string $to_encoding
 * @param int $maxmemory
 * @return string
 */
function createWinCSV(
    $records,
    $delimiter=',', $enclosure='"', $enclosure_escape='""', $line_break="\r\n", 
    $from_encoding='UTF-8', $to_encoding='SJIS-win', 
    $maxmemory=5242880
        ){
    $fp = fopen("php://temp/maxmemory:" . $maxmemory, 'r+b');
    $delimiter = $enclosure . $delimiter . $enclosure;
    foreach ($records as $record) {
        $line = $enclosure
                . implode($delimiter, array_map(
                    function($val) use($enclosure, $enclosure_escape) 
                        {return str_replace($enclosure, $enclosure_escape, $val);}, 
                    $record))
                . $enclosure
                . $line_break;
    	fwrite($fp, $line);
    }
    rewind($fp);
    $tmp = stream_get_contents($fp);
    fclose($fp);
    return mb_convert_encoding($tmp, $to_encoding, $from_encoding);
}

使用例

$records = [
    ['id', 'name', 'birthday', 'comment'],
    ['0001', '佐藤', '1980/01/02', 'Thanks!'],
    ['0002', '鈴木', '1990/03/04', 'Hello.'],
    ['0003', '田中', '2000/05/06', 'I say "Hello".']
];

print(createWinCSV($records));
# "id","name","birthday","comment"
# "0001","����","1980/01/02","Thanks!"
# "0002","���","1990/03/04","Hello."
# "0003","�c��","2000/05/06","I say ""Hello""."

参考

生成したCSVデータをCSVファイルとしてダウンロードする箇所は、次のページを参考にさせて頂いた。
【PHP】【CakePHP】CSVダウンロード - Qiita

備考

本記事はブログ「雑用エンジニアの技術ノート」からの移行記事です。先のブログは削除予定です。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?