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.
2 Answers
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();
4 Comments
Aaron
Thanks. 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.
Mark Baker
You realise that it could be incredibly memory-hungry, holding the entire file in PHP memory
Aaron
A fair question. Thanks for the advice.
frak
It 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.
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);
2 Comments
Angry 84
This 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.
LSerni
The 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.