Tutorials, PHP & MySQL

Ever wanted to save a page to a word doc file? this tutorial shows you just how easy it is to do.

I needed to save a page that is dynamically driven from a database and save it's contents to a doc file so I search Google, I saw lots of articles talking about com classes and third party extensions and applications/api's for something this light it should need all that.... and it doesn't it turns out using the very super friendly header tag that's built into php will do the job perfectly.

Set 2 headers using Content-type and set to application/vnd.ms-word and the second Content-Disposition creates the attachment then you can name the file anything you like followed by .doc in this case yourcoolwordfile.doc.

Note, make sure there is nothing being shown on screen before the headers or you will produce errors.

<?php
    header("Content-type: application/vnd.ms-word");
    header("Content-Disposition: attachment; Filename=yourcoolwordfile.doc");
?>

Then start your normal html markup

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<p>So the page is created correctly place the following meta tag in your header markup</p>

<meta http-equiv="Content-Type" content="text/html; charset=Windows-1252">

Then inside the body tags put what you would like to be displayed in the doc file such as:

<h1>Your very cool web page in Word!</h1>
<p>This text could quite easily from directly from a database....oh the possibilities.</p>
<p>This is a very simple example of creating a doc file with php.</p>

That's all there is to it. Here's a sample script:

<?php
    header("Content-type: application/vnd.ms-word");
    header("Content-Disposition: attachment; Filename=yourcoolwordfile.doc");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Windows-1252">
</head>
<body>

<h1>Your very cool web page in Word!</h1>
<p>This text could quite easily from directly from a database....oh the possibilities.</p>
<p>This is a very simple example of creating a doc file with php.</p>

</body>
</html>