Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Word, send generated file to browser as output without saving it on disc

Tags:

php

phpword

I'm using PHP Word & htmltodocx_converter to create a word document, all works well but I just need an example of how I can send the file to browser for download without saving it on disc. All examples I see you save the file to your disc:

// Save File
$h2d_file_uri = tempnam( "", "htd" );
$objWriter = PHPWord_IOFactory::createWriter( $phpword_object, "Word2007" );
$objWriter->save( $filename ); // At this line, I would like to output the file to the browser

Anyone knows of how I can output the file to the browser on the fly?

like image 827
Morgs Avatar asked Nov 23 '15 13:11

Morgs


1 Answers

This below example maybe works, but to get the expected behaviour of the download in all browsers, the Content-Type header has to be correct for Word2007. Maybe you will need some additional headers for proper output.

You can try this:

$filename = "YOUR_Filename.docx";
header( "Content-Type: application/vnd.openxmlformats-officedocument.wordprocessing‌​ml.document" );// you should look for the real header that you need if it's not Word 2007!!!
header( 'Content-Disposition: attachment; filename='.$filename );

$h2d_file_uri = tempnam( "", "htd" );
$objWriter = PHPWord_IOFactory::createWriter( $phpword_object, "Word2007" );
$objWriter->save( "php://output" );// this would output it like echo, but in combination with header: it will be sent

Thanks to @jamsandwich: The correct header for Word 2007 should be application/vnd.openxmlformats-officedocument.wordprocessing‌​ml.document.

Reference Microsoft

like image 137
swidmann Avatar answered Oct 13 '22 00:10

swidmann