PHPWord any way to not write file to disk when downloading file

Viewed 1839

I'm using PHPWord to generate Word documents, and I'm hoping someone can help on this. The way its set up now, an ajax request is sent to my server from the browser requesting the PHPWord document to be built. The document is built, and stored in a file on the server with this code:

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$fileName = $picklistDetails['file_name'] . ".docx";
$filePath = '../users/' . $userId . "_word_" . $fileName;
$objWriter->save($filePath); 

To allow the user to download the file, once the ajax request succeeds i use window.location to send the user to a page that puts the word document together with this (allowing the download to commence):

$fileName = $this->session->word_file_name;
$filePath = $this->session->word_file_path;

header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=" . $fileName);
header("Content-Transfer-Encoding: binary");    
readfile($filePath);

This all works great, the only problem is i would really rather the file not have to be saved to the server before the download. I've been researching PHPWord and as per this post (Auto download the file attachment using PHPWord) theres some discussion of how you can send the file to php's output stream instead of writing it to disk, but because building the word document is done in ajax and then a separate page is used to download it, i don't think this would work. Am i wrong?

Also in this post (Save Generated File to database PHPWORD) there is a description of how to store it to a DB, but there's still the intermediate step of a file on the server, which i need to avoid.

Is there some way I can modify

$objWriter->save($filePath); 

to not write it to disk and instead save it to a variable or something? Then I could maybe store in a database where I could encrypt it.

Any help would be appreciated. I'm kind of a beginner php programmer so detailed help would be much appreciated. have a good day.

1 Answers

Should be as simple as doing $objWriter->save("php://output");:

$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$fileName = $picklistDetails['file_name'] . ".docx";
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=" . $fileName);
header("Content-Transfer-Encoding: binary");    
$objWriter->save("php://output");

Skip the redirect entirely. Just window.location directly to the above code ^ and the file should download once it's done building.

Related