Saving a PHP File as a Word Document

March 26th, 2009
By: Cory Mathews

So you are looking for a way to save a PHP page as a word doc programatically? Then you have come to the right place.

When I had to overcome this problem my main requirement was that I could not open word on the server.

Searching around the net produced countless pages with the same responses of using COM or using some third party library’s and software. However as with any project if it is possible I, as well as many other developers, try to avoid third party products.

I eventually came up with this solution:

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

Then along with your meta tags add the following

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

Placing this meta tag on a page will cause the browser to think it is a html word document. Thus prompting you to open/save the document instead of rendering it like a normal webpage.

The only downside to this is that when you open the file in word it will open in the web layout mode of word instead of print layout.

Example Usage:

You can view a demo of this in use over at iSearchNotes.com

Word Page: (SaveAsWordDoc.php)

<?php
	header("Content-type: application/vnd.ms-word");
	header("Content-Disposition: attachment; Filename=SaveAsWordDoc.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\">
<title>Saves as a Word Doc</title>
</head>
<body>
<h1>Header</h1>
  This text can be seen in word
<ul>
<li>List 1</li>
<li>List 2</li>
</ul>
</body>
</html>

Calling Page:
Just your normal html link.

link