PHPWord is a powerful open-source API, written in PHP to create and read file-formats including DOC, DOCX, ODT, RTF, HTML, and PDF. Using the API you can create a document, set document properties, insert images, insert charts and more. Let’s get started with creating a simple DOCX file using PHPWord.

Pre-Requisites

To create a word document using the PHPWord you need the following resources installed in your operating system:

composer require zendframework/zend-escaper
composer require zendframework/zend-stdlib

How to Install PHPWord

After that, you have your pre-requisites ready, you can install PHPWord using a simple composer command:

composer require phpoffice/phpword

Create a Word Document using PHP

Creating a word document is simple. You need to create a new document using PhpWord() method, create a new section using addSection() method and add text in it using addText() method. The following is the code snippet to create a simple word document.

<?php
require_once 'vendor\phpoffice\phpword\bootstrap.php';

// Create the new document..
$phpWord = new \PhpOffice\PhpWord\PhpWord();

// Add an empty Section to the document
$section = $phpWord->addSection();
// Add Text element to the Section
$section->addText(
    'File Format Developer Guide - '
    . 'Learn about computer files that you come across in '
    . 'your daily work at: www.fileformat.com'
);
// Save document
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('D:\HelloWorld.docx');

The following is the output document:

See also