10
17

More than 3 years have passed since last update.

PHPでCSVダウンロード

Posted at

PHPでCSVダウンロード

PHPでCSVダウンロードする際のモジュール

UTF-8で出力する場合

function export($file_name, $data)
{
    $fp = fopen('php://output', 'w');

    foreach ($data as $row) {
        fputcsv($fp, $row, ',', '"');
    }
    fclose($fp);
    header('Content-Type: application/octet-stream');
    header("Content-Disposition: attachment; filename={$file_name}");
    header('Content-Transfer-Encoding: binary');
    exit;
}

SJIS-winで出力する場合

function export($file_name, $data)
{
    $fp = fopen('php://output', 'w');

    // UTF-8からSJIS-winへ変換するフィルター
    stream_filter_append($fp, 'convert.iconv.UTF-8/CP932//TRANSLIT', STREAM_FILTER_WRITE);

    foreach ($data as $row) {
        fputcsv($fp, $row, ',', '"');
    }
    fclose($fp);
    header('Content-Type: application/octet-stream');
    header("Content-Disposition: attachment; filename={$file_name}");
    header('Content-Transfer-Encoding: binary');
    exit;
}
10
17
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
10
17