-1

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!

1 Answer 1

1

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));
Sign up to request clarification or add additional context in comments.

2 Comments

This is perfect! Is there a way though that I can only trim the first and last lines of the file?
Instead of foreach do it with $contents[0] and $contents[count($contents) - 1]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.