开发者

How to Prompt Save As Dialog Box After Creating Word Document With Fopen and Fwirte in PHP

I wrote the following script so that an end-user can create a word document from text entered into a textarea:

$fp = fopen("yourDoc.doc", 'w+');
fwrite($fp, $wordDoc);
fclose($fp);

Basically, the file being created is "yourDoc.doc", and the text written to the file is located in the $wordDoc variable.

Currently, this script creates the document and automatically saves it to the same path where my server pages are located. What I want to do is use the above script, but prompt a "Save As" dialog box so that the end-user can save the document to their computer locally.

After a few hours of research, I saw that I could use headers, however I am unable to make them work. I cannot seem to find an example that includes headers, fopen, and fwrite altogether. For example, I tried many variations of the following script with no luck:

$fp = fopen("yourDoc.doc", 'w+');
fwrite($fp, $wordDoc);
fclose($fp);
header('Content-type: application/ms-word');
header('Content-disposition: attachment; filename="yourDoc.doc"');
readfile("yourDoc.doc");

I also tried the following (this is my entire php page):

<?php
//Connect to Db开发者_运维技巧//
$con = mysql_connect("localhost", "root", "admin");
//Verify connection//
if (!$con)
{
  die('Could not connect: ' . mysql_error());
}
//Select Db//
mysql_select_db("schooldb", $con);
$wordDoc = $_GET['word'];//text for word doc//
header('Content-type: application/ms-word');
header('Content-disposition: attachement; filename="yourDoc.doc"');
$fp = fopen("yourDocument.doc", 'w+');//word doc created//
fwrite($fp, $wordDoc);//text written to word doc//
fpassthru($fp);
fclose($fp);
mysql_close($con);  
?>

Does anyone see something wrong with this? The file ends up on my server, and I do not get a Save As dialog box.

I really need help on this.

Thanks,


There's no need to write the word data out to a file first:

header('Content-type: application/ms-word');
header('Content-disposition: attachment; filename="yourDoc.doc"');
echo $wordDoc;

however, you have to ensure that no output whatsoever has occured before you do the header() calls. PHP will NOT send headers if even a single character of "output" has occured, and this will fail.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜