11

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?

1
  • 2
    possibly you can pass in php://output as $filename, if not just create a normal file, create the correct headers, read it to output with readfile then delete it with unlink
    – Steve
    Nov 23, 2015 at 13:56

1 Answer 1

10

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

2
  • 1
    The content type for Word 2007 is application/vnd.openxmlformats-officedocument.wordprocessingml.document (reference) Aug 23, 2017 at 1:34
  • Note the file extension should also be .docx for a Word 2007+ document, rather than .doc Aug 24, 2017 at 3:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.