PHP Classes
PHP Classes
elePHPant
Icontem

How to Create a Ms Word Document using PHP in 2019 Very Quickly

Recommend this page to a friend!
  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog How to Create a Ms Wo...   Post a comment Post a comment   See comments See comments (1)   Trackbacks (0)  

Author:

Updated on: 2019-07-22

Posted on:

Categories: PHP Tutorials

Many PHP applications need to generate word processing documents in Microsoft Word format so they can be served to the application users in a way that their browser can make it opens in the Microsoft Word program.

Fortunately, nowadays this is very simple. Read this article to learn how to can do it with a few lines of PHP code.


 



Setup the Document HTTP Response Headers

The first thing you need to know is that to make the users' browsers open file your application serves for download, is that it needs to set the appropriate HTTP headers to specify a content type that usually the browser is configured to open using Microsoft Word.

So, first set the headers Content-type to application/vnd.ms-word and Content-Disposition to make the browser understand that the data being served is a attached for download with a given file name, in the following example it is yourcoolwordfile.doc.

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

Serve the Document in HTML Format

Then you need to serve the document data like a regular HTML page with the correct meta tags like this:

<!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>

Serve the Document like a Regular HTML Page

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

<body>
<h1>My Word File created with PHP</h1>
<p>This is a text</p>
<p>This is another paragraph.</p>
</body>

Conclusion

Very simple huh? Just tun the code above to see it serving a DOC file that is opened in the Microsoft Word programs in the platforms that have that application available.




You need to be a registered user or login to post a comment

1,543,548 PHP developers registered to the PHP Classes site.
Be One of Us!

Login Immediately with your account on:

FacebookGmail
HotmailStackOverflow
GitHubYahoo


Comments:

1. Don't understand this article - ignasi (2019-07-23 03:17)
unuseful... - 0 replies
Read the whole comment and replies



  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog How to Create a Ms Wo...   Post a comment Post a comment   See comments See comments (1)   Trackbacks (0)