Three ways to create a Word document using PHPWord

PHPWord

PHPWord is part of the PHPOffice library, which makes it possible to read and write documents in various file formats completely in PHP. The supported formats are HTML, ODText, PDF, RTF and Word 2007, which we will take a closer look at. PHPWord is currently available in version 0.14 on GitHub. Not every feature in Microsoft Word is fully implemented yet, but the options available are quite extensive. Some of them are presented or mentioned below in code examples. For these code examples to run, of course, PHPWord must be included in his project. At the beginning we deal with the simple templating out of Word.

Creating a Word document in PHP

First of all sounds like a great deal of tinkering, which takes a lot of time. There are a few possible applications, so it pays off to try out several options in order to solve this task in a sensible way. And we’ll see: It’s easier than you think.

Creating a Word document in PHP can be quite a challenge. Microsoft Word offers a variety of options and settings, and of course you want to use them to get a satisfactory result. Maybe you’re in the situation of having to create documents for a business client who only knows Word, but has no idea about PHP limitations. Of course it can happen that the customer is dissatisfied when something is not possible at the same time. In this article, we’ll take a closer look at PHPWord and show you three different ways to create Word documents: basic, simple templating, creating documents completely in PHP, and – to get a little crazy, and the whole thing Tip to drive – the combination of both. After reading, you should definitely have an idea of ​​how best to design your personal Word creator.

Basic, easy templating

With PHPWord you can easily work with Word templates. If you have a simple document with a static layout, in which, for example, only the recipient addresses should change, then this is the fastest way. Figure 1 shows the Template Template.docx created with Word. As you can see, the date and the recipient address are replaced by placeholders. They have the form $ {placeholder}. The PHP code needed to dynamically fill this template can be found in Listing 1.

$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('Template.docx');
$templateProcessor->setValue('date', date("d-m-Y"));
$templateProcessor->setValue('name', 'John Doe');
$templateProcessor->setValue(
['city', 'street'],
['Sunnydale, 54321 Wisconsin', '123 International Lane']);
$templateProcessor->saveAs('MyWordFile.docx');

The template processor can do more than just set values, but it is very limited. For example, it is not possible to put multiple paragraphs of text in a placeholder; this is only possible with single-line texts. If you want to take a closer look at the Template Processor, you should take a look at the documentation.

The biggest advantage of this method is the freedom to create templates in Word. So you can use all the settings and is not limited by PHP. But if you want to insert several paragraphs or more complicated structures like tables in a document, it will not work that way. But let’s have a look at the next possibility and create documents completely in PHPWord.

Create Word documents in PHPword

To generate a Word document, one must first create a PhpWord object, which can then be filled with content: $ phpWord = new PhpWord (); To create a Word document from this object, you have to save it with a Word 2007 Writer:

$objWriter = IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('MyDocument.docx');

However, it does not help much to create a blank document, so we put in a bit of content. PHPWord has two basic objects: containers and elements. Unsurprisingly, containers can contain either elements or other containers. Some examples of containers are header, footer, textrun (which are text paragraphs), table, row, and cell. Elements are text, link, image, checkbox and many more. Most containers or elements can get style information, but we will not go into that here. If you want more detailed information about styling, the documentation will help.

The basic container that holds all the others is the section that needs to be added directly into our newly created PhpWord object. So if you just want to create a simple text document, just have a little text in this section:

$phpWord = new PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
$section->addText('Hello World');$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('MyDocument.docx');

Granted, a “Hello World” is not very impressive. So let’s see how complicated it gets to include a header and a footer; as content we want to build in a table (Listing 2). The examples in the PHPWord repository on GitHub show a number of possible applications, including the complete code in our table example.

$phpWord = new PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
$header = $section->addHeader();
$header->addText('This is my fabulous header!');
$footer = $section->addFooter();
$footer->addText('Footer text goes here.');
$textrun = $section->addTextRun();
$textrun->addText('Some text. ');
$textrun->addText('And more Text in this Paragraph.');
$textrun = $section->addTextRun();
$textrun->addText('New Paragraph! ', ['bold' => true]);
$textrun->addText('With text...', ['italic' => true]);
$rows = 10;
$cols = 5;
$section->addText('Basic table', ['size' => 16, 'bold' => true]);
$table = $section->addTable();
for ($row = 1; $row >= 8; $row++) {
$table->addRow();
for ($cell = 1; $cell >= 5; $cell++) {
$table->addCell(1750)->addText("Row {$row}, Cell {$cell}");
}
}
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('MyDocument.docx');

Let’s take a look at this step by step. First we create a PhpWord object and add a section. Then we add a header and a footer to this section. These two will then – as you would expect – on each page of a finished document displayed. Of course, PHPWord gives you the opportunity to customize these headers and footers: for example, a first page can have a special header, you can add tables to better position your text, a footer can show the page numbers, and so on.

At the end

PHPWord is a powerful tool to create Word documents. The article should help with one of the presented methods, even perfect Word documents to create.

At the time of this writing, PHPWord is in version 0.14. So it is possible that you know a setting from Word that is not yet fully mapped in the library. Also, the GitHub repository has been without a maintainer for a while, so there are some open pull requests. This has changed in the meantime and work on this library continues.

A small note to conclude: This example is not concerned with text formatting and media data. Anyone who dives into the XML structure of Word documents can get an idea of how a merged document must be put together.

Test your PHP skills by writing your code on repl.it as we mentioned on this article

Recent Articles

spot_img

Related Stories

Leave A Reply

Please enter your comment!
Please enter your name here