[ACCEPTED]-Create Word Document using PHP in Linux-document

Accepted answer
Score: 35

real Word documents

If you need to produce "real" Word 13 documents you need a Windows-based web server 12 and COM automation. I highly recommend Joel's article on 11 this subject.

fake HTTP headers for tricking Word into opening raw HTML

A rather common (but unreliable) alternative 10 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 9 should be in the same file.

Note that this 8 does not send an actual Word document. It merely 7 tricks browsers into offering it as download 6 and defaulting to a .doc file extension. Older 5 versions of Word may often open this without 4 any warning/security message, and just import 3 the raw HTML into Word. PHP sending sending 2 that misleading Content-Type header along does not constitute 1 a real file format conversion.

Score: 35

PHPWord can generate Word documents in docx format. It 5 can also use an existing .docx file as a 4 template - template variables can be added 3 to the document in the format ${varname}

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

Score: 20

OpenOffice templates + OOo command line 3 interface.

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

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

May 1 be that helps.

Score: 10

By far the easiest way to create DOC files 8 on Linux, using PHP is with the Zend Framework 7 component phpLiveDocx.

From the project web site:

"phpLiveDocx 6 allows developers to generate documents 5 by combining structured data from PHP with 4 a template, created in a word processor. The 3 resulting document can be saved as a PDF, DOCX, DOC 2 or RTF file. The concept is the same as 1 with mail-merge."

Score: 8

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

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

It 5 can add or delete pictures. The created 4 document can be produced as a HTML download, a 3 file saved on the server, or as binary contents 2 in PHP.

It can also merge OpenDocument files 1 (ODT, ODS, ODF, ...)

http://www.tinybutstrong.com/opentbs.php

Score: 6

Following on Ivan Krechetov's answer, here 8 is a function that does mail merge (actually 7 just simple text replace) for docx and odt, without 6 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 5 replace [Person Name] with Mina and [Person 4 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 3 can corrupt the document if the string to 2 replace is too general. Try to use verbose 1 replacement strings like [Person Name].

Score: 3

The Apache project has a library called 8 POI which can be used to generate MS Office 7 files. It is a Java library but the advantage 6 is that it can run on Linux with no trouble. This 5 library has its limitations but it may do 4 the job for you, and it's probably simpler 3 to use than trying to run Word.

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

Score: 3
<?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);
?> 

0

Score: 0

There are 2 options to create quality word 4 documents. Use COM to communicate with 3 word (this requires a windows php server 2 at least). Use openoffice and it's API 1 to create and save documents in word format.

Score: 0

Take a look at PHP COM documents (The comments 1 are helpful) http://us3.php.net/com

More Related questions