I am using Laravel-Excel to export a CSV file with a header and footer row. The header and footer rows only have 2-3 columns, however body rows have multiple additional columns - resulting in additional trailing commas at the end of the header and footer.
Since the Laravel-Excel package cannot remove these additional commas, I need to, once the file has been exported, open it somehow via the code, remove the trailing commas from the header and footer rows and then re-save the file and let my users download the end result.
So what I am looking for is:
Actual:
Header,20211021,065529,,,,,,,,,,,,,,,,,,,,,,
Footer,49,,,,,,,,,,,,,,,,,,,,,,,
Required:
Header,20211021,065529
Footer,49
So the process would be as follows:
- Generate the export file using Laravel-Excel
- Save the generated file to the server
- Open the generated file, determine the last line
- Remove the trailing commas from line 1 (header)
- Remove the trailing commas from the last line (footer)
- Overwrite/save the existing csv file
Any help on how I would go about this would be hugely helpful!
CodePudding user response:
I think the easiest way to reach this is using simple php. Via rtrim
its very easy to accomplish this:
$contents = file('file.csv');
foreach ($contents as &$line) {
$line = rtrim($line, ",\r\n");
}
file_put_contents('file.csv', implode("\n", $contents));