Create Word Document using PHP in Linux [closed]
Asked Answered
O

10

60

Whats the available solutions for PHP to create word document in linux environment?

Obliquity answered 24/9, 2008 at 1:52 Comment(0)
U
36

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.

Upstart answered 8/11, 2011 at 3:58 Comment(3)
This is the answer :) The same place has libraries for generating Excel and PowerPoint documents.Pinnatiped
Agreed - this is the correct answer.Freya
I found an updated link of PHPWord and PHPOffice in GitHub.Niela
O
35

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.

Omnibus answered 24/9, 2008 at 2:7 Comment(6)
Problem with this approach is that I can't embed graph in my document.Obliquity
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.htmlOmnibus
For a more elaborate explanation of the technique mentioned above, check this article - codeproject.com/kb/office/Wordyna.aspxLunch
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=304Indisposition
this beats document creators, or having to use internal function to format pages.Geocentric
How can i save this file to my server directory instead of prompting to downloading it?Woodprint
H
20

OpenOffice templates + OOo command line 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 available to ease each of those steps.

May be that helps.

Hawkshaw answered 25/9, 2008 at 8:5 Comment(2)
Could you share which libraries you use, or think are good for these tasks?Bornstein
tinybutstrong.com/plugins/opentbs/tbs_plugin_opentbs.htmlHawkshaw
M
10

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

Mesics answered 14/5, 2009 at 6:48 Comment(2)
Seems to require signing up to a 3rd party service for API access that does the heavy lifting.Hebe
not a component but a web service, perhaps better is phpdocx.com/features?Defibrillator
P
8

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

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

Palladio answered 31/3, 2011 at 22:40 Comment(0)
D
6

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

Duel answered 9/11, 2010 at 21:37 Comment(1)
Great solution. Note that the tempnam_sfx function is not standard PHP, you need to add it from e.g. https://mcmap.net/q/122352/-giving-uploaded-images-a-unique-name-for-mysqli. I also fixed an error in the example.Redneck
H
3

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.

Harilda answered 24/9, 2008 at 14:38 Comment(0)
P
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);
?> 
Pixilated answered 24/7, 2010 at 2:4 Comment(1)
COM will work on Windows only. Plus the server must have MS Word installed.Tiernan
E
0

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.

Earwitness answered 24/9, 2008 at 7:33 Comment(0)
A
0

Take a look at PHP COM documents (The comments are helpful) https://www.php.net/com

Affirmation answered 26/11, 2010 at 15:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.