Skip to content

Instantly share code, notes, and snippets.

@nobodyplace
Last active December 8, 2021 08:26
Show Gist options
  • Save nobodyplace/ab23d1d836c361f977479e3641920807 to your computer and use it in GitHub Desktop.
Save nobodyplace/ab23d1d836c361f977479e3641920807 to your computer and use it in GitHub Desktop.
<?php
class makeCsv
{
public function arrangeData()
{
try {
//サンプルデータ
//$_POST['data']
$post_data = [
['お客様ID', '購入金額', '購入日付'],
[1, 1200, '2021/12/08 17:15'],
[2, 2700, '2021/12/09 11:45'],
[3, 1500, '2021/12/09 13:35']
];
//Windows向け設定
$delimiter = ',';
$enclosure = '"';
$enclosure_escape = '""';
$line_break = "\r\n";
//データをCSV用にアレンジ
$csv = '';
foreach($post_data as $row) {
$values = [];
foreach($row as $value) {
$values[] = $enclosure.str_replace($enclosure, $enclosure_escape, $value).$enclosure;
}
$csv .= implode($delimiter, $values).$line_break;
}
header('Content-Type: application/octet-stream');
header('Content-disposition: attachment; filename=temp.csv');
echo json_encode($csv);
} catch (\Exception $e) {
http_response_code(400);
echo json_encode([
'status' => false,
'message' => $e->getMessage()
]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment