Search code examples
phphtmlfilegenerated

Generating a doc file from a php "results" page?


I have a PHP generated page containing the results of a submitted form, what I would like to do is save this as a .doc file on the server. After some googling I came across this code which I adapted:-

$myFile = "./dump/".$companyName."/testFile.doc";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
$stringData = "Tracy Tanner\n";
fwrite($fh, $stringData);
fclose($fh);

But the problem with this is that I would have to recreate the results in order to manually write them to the file and it doesn't seem very efficient.

So I continued to google and found the PHP manual which left me scratching my head frankly, however I eventually found this:-

ob_start();
// code to generate page.
$out = ob_get_contents();
ob_end_clean();
// or write it to a file.
file_put_contents("./dump/".$companyName."/testFile.doc",$out);

Which will create the file, but doesn't write anything to it. However this seems to be the way to do what (Based on the PHP manual) I want even if I can't get it to work!

Any advice? I don't mind googling if I can figure out a decent search term :)


Solution

  • This sould do it for you:

    $cache = 'path/to/your/file';
    
    ob_start();
    
    // your content goes here...
    echo "hello !"; // would put hello into your file
    
    $page = ob_get_contents(); 
    
    ob_end_clean(); 
    
    $fd = fopen("$cache", "w"); 
    
        if ($fd) {
    
        fwrite($fd,$page); 
    
        fclose($fd);
    
    }
    

    It's also a great way to cache dynamic pages. Hope it helps.