6

Is this possible? or must one use a PHP library such as thephpleague/csv?

Example, according to PhpSpreadsheet's documentation:

$reader      = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
$spreadsheet = $reader->load($file);

$writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);
$writer->setUseBOM(true);
$writer->setDelimiter(',');
$writer->setEnclosure('');
$writer->setLineEnding("\r\n");
$writer->setSheetIndex(0);

$writer->save('test.csv');

As you can see this completely counter-productive as the load() method requires an actual $file to do essentially the same thing.

Is there a way to use PhpOffice\PhpSpreadsheet\Writer\Csv() without using the spreadsheet and instead using a string containing CSV data?

Thanks in advance for all positive inputs and suggestions.

2 Answers 2

4

You don't need to load a file, you can create an empty Spreadsheet object directly by using

$spreadsheet = new PhpOffice\PhpSpreadsheet\Spreadsheet();

as shown in the "Hello World" example in the PHPSPreadsheet documentation

But if all you want to do is write a csv file; then you're far better using PHP's built-in fputcsv() function than a library designed to manipulate genuine spreadsheets with multiple worksheets, formatting, formulae, and working with multiple different file formats, etc.

Or for simply writing a string that's already concatenated (are you sure that you've quoted everything that needs quoting, and escaped everything that needs escaping), just use fwrite().

Counter-productive is building your own csv string and then using a spreadsheet library to write each line.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the straightforward explanation and input! Exactly what I was looking for as an answer :]
1

from the docs: https://phpspreadsheet.readthedocs.io/en/latest/topics/reading-and-writing-to-file/#csv-comma-separated-values

You can also treat a string as if it were the contents of a CSV file as follows:

$reader = new \PhpOffice\PhpSpreadsheet\Reader\Csv();
$spreadsheet = $reader->loadSpreadsheetFromString($data);

Comments

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.