Home > Enterprise >  Edit an existing exported csv file via PHP / Laravel and re-save
Edit an existing exported csv file via PHP / Laravel and re-save

Time:10-28

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:

  1. Generate the export file using Laravel-Excel
  2. Save the generated file to the server
  3. Open the generated file, determine the last line
  4. Remove the trailing commas from line 1 (header)
  5. Remove the trailing commas from the last line (footer)
  6. 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));
  • Related