1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| use Hyperf\HttpMessage\Stream\SwooleStream; use Hyperf\HttpServer\Response;
class ExportLogic { public static function export(array $head, array $body, string $file_name) { $head_keys = array_keys($head); $head_values = array_values($head); $fileData = self::utfToGbk(implode(',', $head_values)) . "\n";
if (strpos($file_name, '.') === false) { $file_name .= '.csv'; }
foreach ($body as $value) { $temp_arr = []; foreach ($head_keys as $key) { $temp_arr[] = $value[$key] ?? ''; } $fileData .= self::utfToGbk(implode(',', $temp_arr)) . "\n"; }
$response = new Response(); $content_type = 'text/csv'; return $response->withHeader('content-description', 'File Transfer') ->withHeader('content-type', $content_type) ->withHeader('content-disposition', "attachment; filename={$file_name}") ->withHeader('content-transfer-encoding', 'binary') ->withHeader('pragma', 'public') ->withBody(new SwooleStream($fileData)); }
public static function utfToGbk($data) { return mb_convert_encoding($data, "GBK", "UTF-8"); } }
|