Author: Clement Sam
Viewers: 1,919
Last month viewers: 475
Categories: PHP Tutorials
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,616,405 PHP developers registered to the PHP Classes site.
Be One of Us!
Login Immediately with your account on:
Comments:
1. Don't understand this article - ignasi (2019-07-23 03:17)
unuseful... - 0 replies
Read the whole comment and replies