Rectangle 27 0

Create Word Document using PHP in Linux?


"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."

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:

Seems to require signing up to a 3rd party service for API access that does the heavy lifting.

not a component but a web service, perhaps better is phpdocx.com/features?

Note
Rectangle 27 0

Create Word Document using PHP in Linux?


Another option would be OpenOffice but I can't exactly recommend it since I've never used it.

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.

Note
Rectangle 27 0

Create Word Document using PHP in Linux?


Agreed - this is the correct answer.

I found an updated link of PHPWord and PHPOffice in GitHub.

It has an LGPL license and the examples that came with the code worked nicely for me.

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}

Note
Rectangle 27 0

Create Word Document using PHP in Linux?


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

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

A rather common (but unreliable) alternative is:

For a more elaborate explanation of the technique mentioned above, check this article - codeproject.com/kb/office/Wordyna.aspx

If you need to produce "real" Word documents you need a Windows-based web server. I highly recommend Joel's article on this subject: joelonsoftware.com/items/2008/02/19.html

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 - kubilayerdogan.net/?p=304

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.

Problem with this approach is that I can't embed graph in my document.

Note
Rectangle 27 0

Create Word Document using PHP in Linux?


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, ...)

No temporary files needed, no command lines, all in PHP.

OpenTBS can create DOCX dynamic documents in PHP using the technique of templates.

Note
Rectangle 27 0

Create Word Document using PHP in Linux?


$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);
}
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;
}

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].

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.

Great solution. Note that the tempnam_sfx function is not standard PHP, you need to add it from e.g. stackoverflow.com/a/37515697/957841. I also fixed an error in the example.

This will replace [Person Name] with Mina and [Person Last Name] with Mooo:

Note
Rectangle 27 0

Create Word Document using PHP in Linux?


  • Create manually an ODT template with placeholders, like [%value-to-replace%]
  • Run the conversion ODT -> DOC via OpenOffice command line interface.
  • 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.

Could you share which libraries you use, or think are good for these tasks?

There are tools and libraries available to ease each of those steps.

Note
Rectangle 27 0

Create Word Document using PHP in Linux?


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

A rather common (but unreliable) alternative is:

For a more elaborate explanation of the technique mentioned above, check this article - codeproject.com/kb/office/Wordyna.aspx

If you need to produce "real" Word documents you need a Windows-based web server. I highly recommend Joel's article on this subject: joelonsoftware.com/items/2008/02/19.html

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 - kubilayerdogan.net/?p=304

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.

Problem with this approach is that I can't embed graph in my document.

Note
Rectangle 27 0

Create Word Document using PHP in Linux?


Agreed - this is the correct answer.

I found an updated link of PHPWord and PHPOffice in GitHub.

It has an LGPL license and the examples that came with the code worked nicely for me.

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}

Note
Rectangle 27 0

Create Word Document using PHP in Linux?


<?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);
?>

COM will work on Windows only. Plus the server must have MS Word installed.

Note