Thursday, May 26, 2011

Generating Doc files from Php in Linux

When we are writing a php application and need to generate a Microsoft word document (.doc) dynamically from the php script we can you this very simple to technique for it. We don't have to learn to use any specialized library for this purpose. Only the knowledge of html and php will be enough for this since all the formattings of the generating .doc file will be done by the basic formattings we do on web pages. However this works only in the linux environment.

Lets say you want to generate a file called "report.doc" with some content in it. Open your favourite text editor and enter the following example code in it. The first two lines in the code make the output of this php script to be appear as Microsoft word .doc file to the web browser which you used to view the output of the script. Inside the body section of this file you can write any kind of php statements you want to echo the required output in a specific format. You can even change the font and background colours also just thinking it as going to be appear in the web browser as usual. These texts in your specified colours and fonts will appear in the final .doc file. 

    After writing down the example code in the file, save it to your web servers web folder (www or htdocs in apache server) with a file name say "gernerator.php". Then access that file from your web browser. You will notice that the web browser is prompting to download and save a file call "report.doc". That's the output generated from the "generator.php" file. Save it somewhere in your PC and open from an application which can be used to open .doc files like OpenOffice or LibreOffice. You will notice that the output of the php script has been written into the .doc file.

When you use this method to generate php scripts, keep in mind that all the things related to the content of the .doc file should appear inside a single php file. You cannot use external CSS files together with the php file. All the styles should be embedded inside the same php file. Because of this reason, you cannot add images to the php file for appearing in the final .doc file.  

1:  header("Content-type: application/");  
2:  header("Content-Disposition: attachment;Filename=report.doc");  
3:  echo "<html>";  
4:  echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";  
5:  echo "<body>";  
6:  //------------------------------------------  
7:  echo "<u><b>Title of the report</b></u>";  
8:  echo "1) Name : Name Of someone";  
9:  echo "2) Age : 23";  
10:  echo "3) Gender : male";  
11:  //------------------------------------------  
12:  echo "</body>";  
13:  echo "</html>";  

No comments:

Post a Comment