After loading a PHPExcel object with my data, I want to output the contents directly into a php variable, instead of writing to a file. Have I missed the method to do that, for it seems that the only way to save is to save to disk.
Asked
Active
Viewed 2.1k times
2 Answers
61
You can use a writer to save to disk, or save to php://output. If the latter, you could use output buffering to capture that output and then store in a variable.... not sure quite why you'd want to do this though.
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
ob_start();
$objWriter->save('php://output');
$excelOutput = ob_get_clean();

Mark Baker
- 209,507
- 32
- 346
- 385
-
3Thanks. If I'm using this inside a framework like symfony, I may need to pass the contents around from an excel service to some type of outputting service or controller. I'd rather avoid the hit of writing to disk. – Aaron Feb 28 '12 at 18:55
-
5You realise that it could be incredibly memory-hungry, holding the entire file in PHP memory – Mark Baker Feb 28 '12 at 21:12
-
A fair question. Thanks for the advice. – Aaron Feb 29 '12 at 02:02
-
1It is worth noting that a fair number of the writers (but not all) will detect if you are writing to "php://output" or "php://stdout" and it will use a temp file during creation and then copy the contents of that file to the specified stream, so you might as well just pick a temp file and use that directly. – frak Feb 15 '18 at 16:58
3
Since PHPExcel writes the file to the disk in any case, if you capture stdout, what happens internally is that the file is written to the disk, then read from the disk (and deleted), printed to stdout and then captured in the output buffer.
You might as well do:
$tmpfile = tempnam($tmp_dir, 'phpxltmp');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save($tmpfile);
$excelOutput = file_get_contents($tmpfile);
unlink($tmpfile);

Arno Schäfer
- 277
- 2
- 8
-
3This is sort of common sense on how one might approach this, But there are plenty of downsides to this method.. Your creating/using the disk which requires more operations/time/space. If this script is run in multiple instances or overlaps, you need to generate a different file per instance. This can lead to corruption/acess issues. The OP had said directly to a variable, not to a file then to a variable. – Angry 84 Jul 13 '17 at 04:24
-
1The answer already addresses these downsides. `tempnam` creates a different file per instance, and since PHPExcel uses a file in any case, it is the apparently "straight to variable" approach that is the less efficient of the two. In many cases, it would be possible to use `readfile` or stream handling to sidestep memory issues and further increase performances. While the accepted answer appears to be more straightforward, which is valuable in itself, I still feel that *this* should be the accepted answer, or a credible alternative. – LSerni Oct 20 '17 at 07:47