File::create without source - using F::write too?

I am currently creating a CSV file programmatically and then adding it to Kirby using File::create(). Is there a better way to do this? Is there any way to create a file without an existing source?

File::create() requires a source file to be provided. Is there a way to create a file without an existing source? kirby/src/Cms/FileActions.php at eb47158e91e74184ab291ede020664f1d2829f74 · getkirby/kirby · GitHub

Could be there a way with using F::write?

        kirby()->impersonate('kirby');

        $csvFilePath = kirby()->root('content') . '/file-csv.csv';

        $csvFile = fopen($csvFilePath, 'w');

        foreach ($data as $row) {
          fputcsv($csvFile, $row);
        }

        fclose($csvFile);

        $file = File::create([
          'source' => $csvFilePath,
          'parent' => site(),
          'filename' => date(format: 'd-m-Y H:i:s') . '-file-csv.csv',
          'template' => 'csv'
        ]);

I came up with a second idea. But is there maybe a smarter way? :)"

   $file = null;
        if (F::write(kirby()->root('content') . '/file-csv.csv', '')) {
          $file = new File([
            'source' => site()->file('file-csv.csv'),
            'parent' => site(),
            'filename' => 'file-csv.csv'
          ]);
        }

        if ($file) {

          $csvFile = fopen($file->root(), 'w');

          foreach ($data as $row) {
            fputcsv($csvFile, $row);
          }

          fclose($csvFile);

          $file->update(['template' => 'csv']);
        }

If you don’t need the file hooks or file validation, you can simply write files directly into the content folder at the right place. Kirby will find that file afterwards just as if you would move it there manually in the finder.

Doing this should be totally enough:

$csvFile = fopen(kirby()->root('content') . '/file-csv.csv', 'w');

foreach ($data as $row) {
  fputcsv($csvFile, $row);
}

fclose($csvFile);

If you want to add the template to it, you could then add:

kirby()->site()->file('file-csv.csv')->update([
  'template' => 'csv'
]);
1 Like