Route with CSV download adds "Not Found" (404 error) into the CSV file

Dear Kirby community,

for a Kirby 3 site, I use this router to export some registration data as CSV file.

        [
      'pattern' => 'api/csv',
      'action' => function() {
        header::download(['mime'=>'application/csv', 'name' => 'regs.csv', 'Pragma' => 'no-cache', 'Content-Disposition' => 'attachment']);
        $regs = site()->index()->find('register/anmeldestatus')->anmeldungen()->yaml();
        $f = fopen('php://output', 'w');
        foreach($regs as $registration) {
            fputcsv($f, $registration, ';','"');
        }
        fpassthru($f);
        return false;
      }
    ]
  ]

The file download works, the CSV file is well formed, but in the last line it contains the words “Not found” or the HTML of an error page, when there is one.

Any idea here on the forum?

Many thanks in advance

Just guessing, but maybe because your return false.

Ah, thanks, yes. Seems, I should add a “new Response”.

Just wonder, what would be the right type for a CSV download…

@texnixe Thank you very much for nudging me in the right direction, replaced my previous response with

return new Response($f, 'application/csv');

Works as expected!

I’m bringing this old thread back up:

In a current project I also need a CSV download and have recycled my old code from 2019.

Unfortunately, I now get the error described in 2019 again when I use the solution that worked back then:

return new Response($f, 'application/csv');

now leads to the following error:

TypeError: Kirby\Http\Response::download(): Argument #1 ($file) must be of type string, resource given, called in /Users/xxx/Sites/xxx/site/config/config.php on line 49 in file /Users/xxx/Sites/xxx/kirby/src/Http/Response.php on line 135
Stack trace:
  1. typeError->() /Users/xxx/Sites/xxx/kirby/src/Http/Response.php:135
  2. Kirby\Http\Response->download() /Users/xxx/Sites/xxx/site/config/config.php:49
  3. Kirby\Http\Route->{closure}() [internal]:0
  4. Closure->call() /Users/xxx/Sites/xxx/kirby/src/Http/Router.php:120
  5. Kirby\Http\Router->call() /Users/xxx/Sites/xxx/kirby/src/Cms/App.php:340
  6. Kirby\Cms\App->call() /Users/xxx/Sites/xxx/kirby/src/Cms/App.php:1239
  7. Kirby\Cms\App->render() /Users/xxx/Sites/xxx/index.php:5
  8. require() /Users/xxx/.composer/vendor/laravel/valet/server.php:110

...

Any idea, what went wrong?