在 Linux 中使用 PHP 创建 Word 文档
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/124959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create Word Document using PHP in Linux
提问by
Whats the available solutions for PHP to create word document in linux environment?
PHP 在 linux 环境中创建 word 文档的可用解决方案是什么?
回答by Sergey Kornilov
real Word documents
真实的Word文档
If you need to produce "real" Word documents you need a Windows-based web server and COM automation. I highly recommend Joel's articleon this subject.
如果您需要生成“真正的”Word 文档,您需要一个基于 Windows 的 Web 服务器和 COM 自动化。我强烈推荐乔尔关于这个主题的文章。
fakeHTTP headers for tricking Word into opening raw HTML
用于欺骗 Word 打开原始 HTML 的伪造HTTP 标头
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 notsend 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.
请注意,这并不会发送实际的Word文档。它只是诱使浏览器将其作为下载提供并默认为.doc
文件扩展名。旧版本的 Word 可能经常在没有任何警告/安全消息的情况下打开它,只需将原始 HTML 导入 Word。PHP 发送该误导性Content-Type
标头并不构成真正的文件格式转换。
回答by DreamWerx
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 个选项可以创建高质量的 Word 文档。使用 COM 与 word 通信(这至少需要一个 windows php 服务器)。使用 openoffice 及其 API 来创建和保存 word 格式的文档。
回答by Mr. Shiny and New 安宇
The Apache project has a library called POIwhich 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.
Apache 项目有一个名为POI的库,可用于生成 MS Office 文件。它是一个 Java 库,但优点是它可以毫无问题地在 Linux 上运行。这个库有其局限性,但它可以为您完成这项工作,而且使用起来可能比尝试运行 Word 更简单。
Another option would be OpenOffice but I can't exactly recommend it since I've never used it.
另一种选择是 OpenOffice,但我不能完全推荐它,因为我从未使用过它。
回答by Ivan Krechetov
OpenOffice templates + OOo command line interface.
OpenOffice 模板 + OOo 命令行界面。
- 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.
- 使用占位符手动创建 ODT 模板,例如 [%value-to-replace%]
- 在 PHP 中使用真实数据实例化模板时,解压缩模板 ODT(它是一个压缩的 XML),并针对 XML 运行用实际值替换占位符的文本。
- 将 ODT 拉回
- 通过 OpenOffice 命令行界面运行转换 ODT -> DOC。
There are tools and libraries available to ease each of those steps.
有一些工具和库可用于简化每个步骤。
May be that helps.
可能有帮助。
回答by Ivan Krechetov
By far the easiest way to create DOC files on Linux, using PHP is with the Zend Framework component phpLiveDocx.
到目前为止,在 Linux 上创建 DOC 文件的最简单方法是使用 PHP 和 Zend Framework 组件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."
“phpLiveDocx 允许开发人员通过将来自 PHP 的结构化数据与在文字处理器中创建的模板相结合来生成文档。生成的文档可以保存为 PDF、DOCX、DOC 或 RTF 文件。其概念与邮件合并相同.”
回答by hoang
<?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);
?>
回答by Matiaan
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.
继 Ivan Krechetov 的回答之后,这里有一个函数可以为 docx 和 odt 进行邮件合并(实际上只是简单的文本替换),而无需额外的库。
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:
这会将 [Person Name] 替换为 Mina,将 [Person Last Name] 替换为 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].
请注意,如果要替换的字符串过于笼统,此函数可能会损坏文档。尝试使用详细的替换字符串,如 [Person Name]。
回答by JREAM
Take a look at PHP COM documents (The comments are helpful) http://us3.php.net/com
看看PHP COM文档(评论很有帮助)http://us3.php.net/com
回答by Skrol29
OpenTBScan create DOCX dynamic documents in PHP using the technique of templates.
OpenTBS可以使用模板技术在 PHP 中创建 DOCX 动态文档。
No temporary files needed, no command lines, all in PHP.
不需要临时文件,不需要命令行,全部在 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.
它可以添加或删除图片。创建的文档可以生成为 HTML 下载、保存在服务器上的文件或 PHP 中的二进制内容。
It can also merge OpenDocument files (ODT, ODS, ODF, ...)
它还可以合并 OpenDocument 文件(ODT、ODS、ODF 等)
回答by Highly Irregular
PHPWordcan 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}
PHPWord可以生成 docx 格式的 Word 文档。它还可以使用现有的 .docx 文件作为模板 - 模板变量可以以 ${varname} 格式添加到文档中
It has an LGPL license and the examples that came with the code worked nicely for me.
它有一个 LGPL 许可证,代码附带的示例对我来说效果很好。