Write Office Documents with PHP

As a followup to the popular article on how to write office documents with ASP, I’ll cover the specific code you’ll need to write MS Office Documents with PHP.

The method we will be using to output Office compatible documents is simple enough – outputting standard HTML. Office has extensive HTML support and will gladly read the HTML you send to Office programs like Word or Excel. The topic we will cover in the article is how to get Word or Excel to open your documents.

The first and easiest method to outputting Word or Excel documents would be to simply save your output structured as text/HTML to a file as you normally would, giving it a Word extension of .DOC or an Excel extension of .XLS. Then you can link to this file and when the user downloads or opens it, it will open in Word or Excel on their computer if they have the program installed.

<?php
$objFile = fopen('FILENAME.DOC', 'w');
fwrite($objFile, $FILECONTENTS);
fclose($objFile);
?>

The second method will take advantage of HTTP headers to tell the browser your scipt will be outputting an Excel or Word document. The browser will then either display or download the content you output.

To tell the browser you will be outputting a Word document, use the following line of code:

header('Content-Type: application/msword');

To tell the browser you will be outputting an Excel document, use the following line of code:

header('Content-Type: application/vnd.ms-excel');

It’s important to note that headers must be sent prior to any other content, so it’s recommended to place this code at the beginning of your script. Another useful header your script can send will force the browser to download and not display the document in browser. The following line of code will do that and even prefill the filename.

header('Content-Disposition: attachment;filename=FILENAME.DOC');

And there you have it. You can now output an HTML formatted document as you normally would and Microsoft Word or Excel will parse and display it.


Posted in: Articles

Write a Comment