Whats the available solutions for PHP to create word document in linux environment?
10 Answers
PHPWord can generate Word documents in docx format. It can also use an existing .docx file as a template - template variables can be added to the document in the format ${varname}
It has an LGPL license and the examples that came with the code worked nicely for me.

- 1
- 1

- 38,000
- 12
- 52
- 70
-
2This is the answer :) The same place has libraries for generating Excel and PowerPoint documents. – Chris Baker Oct 10 '12 at 14:37
-
2Agreed - this is the correct answer. – Felix Eve Dec 02 '13 at 12:24
-
3I found an updated link of [PHPWord](https://github.com/PHPOffice/PHPWord) and [PHPOffice](https://github.com/PHPOffice) in GitHub. – j2gl Aug 10 '15 at 03:14
real Word documents
If you need to produce "real" Word documents you need a Windows-based web server and COM automation. I highly recommend Joel's article on this subject.
fake HTTP headers for tricking Word into opening raw HTML
A rather common (but unreliable) alternative is:
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment; filename=document_name.doc");
echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
echo "<b>Fake word document</b>";
echo "</body>";
echo "</html>"
Make sure you don't use external stylesheets. Everything should be in the same file.
Note that this does not send an actual Word document. It merely tricks browsers into offering it as download and defaulting to a .doc
file extension. Older versions of Word may often open this without any warning/security message, and just import the raw HTML into Word. PHP sending sending that misleading Content-Type
header along does not constitute a real file format conversion.

- 144,265
- 20
- 237
- 291

- 1,772
- 2
- 13
- 22
-
-
2If you need to produce "real" Word documents you need a Windows-based web server. I highly recommend Joel's article on this subject: http://www.joelonsoftware.com/items/2008/02/19.html – Sergey Kornilov Sep 24 '08 at 12:38
-
For a more elaborate explanation of the technique mentioned above, check this article - http://www.codeproject.com/kb/office/Wordyna.aspx – mvark Feb 01 '11 at 02:30
-
If you want to use the above and have some difficult divs to deal with (for me it was a CSS based bar chart) you can use this code to generate a screenshot of the div, upload it to the server, and modify your html to include that image - http://www.kubilayerdogan.net/?p=304 – Dave Hilditch Jul 14 '13 at 14:17
-
this beats document creators, or having to use internal function to format pages. – unixmiah Dec 18 '14 at 18:24
-
How can i save this file to my server directory instead of prompting to downloading it? – jackkorbin Nov 27 '16 at 20:09
OpenOffice templates + OOo command line interface.
- Create manually an ODT template with placeholders, like [%value-to-replace%]
- When instantiating the template with real data in PHP, unzip the template ODT (it's a zipped XML), and run against the XML the textual replace of the placeholders with the actual values.
- Zip the ODT back
- Run the conversion ODT -> DOC via OpenOffice command line interface.
There are tools and libraries available to ease each of those steps.
May be that helps.

- 18,802
- 8
- 49
- 60
-
Could you share which libraries you use, or think are good for these tasks? – Shade Feb 06 '11 at 19:16
-
2http://www.tinybutstrong.com/plugins/opentbs/tbs_plugin_opentbs.html – Ivan Krechetov Feb 09 '11 at 15:32
By far the easiest way to create DOC files on Linux, using PHP is with the Zend Framework component phpLiveDocx.
From the project web site:
"phpLiveDocx allows developers to generate documents by combining structured data from PHP with a template, created in a word processor. The resulting document can be saved as a PDF, DOCX, DOC or RTF file. The concept is the same as with mail-merge."

- 50,140
- 28
- 121
- 140
-
5Seems to require signing up to a 3rd party service for API access that does the heavy lifting. – garrow Jun 09 '09 at 23:46
-
1not a component but a web service, perhaps better is http://www.phpdocx.com/features? – DaveO Aug 31 '11 at 22:06
OpenTBS can create DOCX dynamic documents in PHP using the technique of templates.
No temporary files needed, no command lines, all in PHP.
It can add or delete pictures. The created document can be produced as a HTML download, a file saved on the server, or as binary contents in PHP.
It can also merge OpenDocument files (ODT, ODS, ODF, ...)

- 5,402
- 1
- 20
- 25
Following on Ivan Krechetov's answer, here is a function that does mail merge (actually just simple text replace) for docx and odt, without the need for an extra library.
function mailMerge($templateFile, $newFile, $row)
{
if (!copy($templateFile, $newFile)) // make a duplicate so we dont overwrite the template
return false; // could not duplicate template
$zip = new ZipArchive();
if ($zip->open($newFile, ZIPARCHIVE::CHECKCONS) !== TRUE)
return false; // probably not a docx file
$file = substr($templateFile, -4) == '.odt' ? 'content.xml' : 'word/document.xml';
$data = $zip->getFromName($file);
foreach ($row as $key => $value)
$data = str_replace($key, $value, $data);
$zip->deleteName($file);
$zip->addFromString($file, $data);
$zip->close();
return true;
}
This will replace [Person Name] with Mina and [Person Last Name] with Mooo:
$replacements = array('[Person Name]' => 'Mina', '[Person Last Name]' => 'Mooo');
$newFile = tempnam_sfx(sys_get_temp_dir(), '.dat');
$templateName = 'personinfo.docx';
if (mailMerge($templateName, $newFile, $replacements))
{
header('Content-type: application/msword');
header('Content-Disposition: attachment; filename=' . $templateName);
header('Accept-Ranges: bytes');
header('Content-Length: '. filesize($file));
readfile($newFile);
unlink($newFile);
}
Beware that this function can corrupt the document if the string to replace is too general. Try to use verbose replacement strings like [Person Name].

- 154
- 1
- 8
-
Great solution. Note that the tempnam_sfx function is not standard PHP, you need to add it from e.g. http://stackoverflow.com/a/37515697/957841. I also fixed an error in the example. – Arnout Mar 27 '17 at 08:30
The Apache project has a library called POI which can be used to generate MS Office files. It is a Java library but the advantage is that it can run on Linux with no trouble. This library has its limitations but it may do the job for you, and it's probably simpler to use than trying to run Word.
Another option would be OpenOffice but I can't exactly recommend it since I've never used it.

- 13,822
- 6
- 44
- 64
<?php
function fWriteFile($sFileName,$sFileContent="No Data",$ROOT)
{
$word = new COM("word.application") or die("Unable to instantiate Word");
//bring it to front
$word->Visible = 1;
//open an empty document
$word->Documents->Add();
//do some weird stuff
$word->Selection->TypeText($sFileContent);
$word->Documents[1]->SaveAs($ROOT."/".$sFileName.".doc");
//closing word
$word->Quit();
//free the object
$word = null;
return $sFileName;
}
?>
<?php
$PATH_ROOT=dirname(__FILE__);
$Return ="<table>";
$Return .="<tr><td>Row[0]</td></tr>";
$Return .="<tr><td>Row[1]</td></tr>";
$sReturn .="</table>";
fWriteFile("test",$Return,$PATH_ROOT);
?>

- 32,488
- 9
- 84
- 95

- 31
- 1
-
COM will work on Windows only. Plus the server must have MS Word installed. – Stephan Weinhold Mar 23 '16 at 11:42
There are 2 options to create quality word documents. Use COM to communicate with word (this requires a windows php server at least). Use openoffice and it's API to create and save documents in word format.

- 2,888
- 1
- 18
- 13
Take a look at PHP COM documents (The comments are helpful) http://us3.php.net/com

- 5,741
- 11
- 46
- 84