使用PHP进行CSV下载

使用PHP进行CSV下载

下载CSV文件时使用的PHP模块

如果以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 秒后关闭
bannerAds