Search code examples
phpfiledoc

collect html output of a php script and serve it as doc file


How can i collect all the html content of a php page and save it into a doc file and then serve it to user with save prompt.

<?php
 ob_start();
 echo 'Hello World';
 file_put_contents('filename.doc', ob_get_contents());
 header('Content-type: application/msword'); 
 // serve filename.doc to user with a save promt.?????
 ob_end_flush();
 ?>

Solution

  • First off, it won't be a .doc file. You can't just put any kind of contents in a file, give it a file extension and hope it will work as a .doc file.

    Second - you got it almost all right, up to the part where you need to read the file and force browser to download it. To do so, add this to your code (with necessary changes of course):

    header('Content-Disposition: attachement;filename="put_filename_here.doc"');
    header('Content-Transfer-Encoding: binary');
    
    readfile('/path/to/file.doc');