Files
jongryangje/app/Helpers/export_helper.php

70 lines
2.0 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
/**
* CSV 엑셀 내보내기 헬퍼
*
* UTF-8 BOM 포함으로 한글 엑셀 호환성 보장
*/
if (! function_exists('export_csv')) {
/**
* CSV 파일을 브라우저로 다운로드 전송
*
* @param string $filename 파일명 (확장자 포함, : 'export.csv')
* @param string[] $headers 컬럼 헤더 배열
* @param array $rows 데이터 배열 ( 행은 배열)
*/
function export_csv(string $filename, array $headers, array $rows): void
{
// 파일명에 .csv 확장자 보장
if (! str_ends_with($filename, '.csv')) {
$filename .= '.csv';
}
$response = service('response');
$response->setHeader('Content-Type', 'text/csv; charset=UTF-8');
$response->setHeader('Content-Disposition', 'attachment; filename="' . $filename . '"');
$response->setHeader('Pragma', 'no-cache');
$response->setHeader('Cache-Control', 'no-store, no-cache, must-revalidate');
// UTF-8 BOM (한글 엑셀 호환)
$output = "\xEF\xBB\xBF";
// 헤더 행
$output .= csv_encode_row($headers);
// 데이터 행
foreach ($rows as $row) {
$output .= csv_encode_row(array_values((array) $row));
}
$response->setBody($output);
$response->send();
exit;
}
}
if (! function_exists('csv_encode_row')) {
/**
* 배열 행을 CSV 문자열로 변환
*
* @param array $fields
* @return string
*/
function csv_encode_row(array $fields): string
{
$escaped = [];
foreach ($fields as $field) {
$val = (string) ($field ?? '');
// 쌍따옴표 이스케이프 및 감싸기
if (str_contains($val, '"') || str_contains($val, ',') || str_contains($val, "\n") || str_contains($val, "\r")) {
$val = '"' . str_replace('"', '""', $val) . '"';
}
$escaped[] = $val;
}
return implode(',', $escaped) . "\r\n";
}
}