Getting Started with PHP Word

PHP Word documentation : https://phpword.readthedocs.io/en/latest/installing.html

The library for phpWord can be found here: https://github.com/PHPOffice/PHPWord

Sample codes : https://github.com/PHPOffice/PHPWord/tree/develop/samples

A nice tutorial to beginwith https://redstapler.co/phpword-intro/

Install PHPWord via Composer (Composer is a Dependency Manager Tool for PHP. Like npm for Node.js) Add the below code to your composer.json file.

{
    "require": {
       "phpoffice/phpword": "v0.17.*"
    }
}

In command prompt and type below to trigger the install.

composer install

Composer will pull PHPWord and all its dependencies to your project location. Now we’re ready to move forward with the code. For Example, here is the steps if you want to create a new docx document with “Hello Word” text.

/*********************step 1: autoload***********************************/
require_once 'vendor/autoload.php';
/********************************************************/


/**********************step 2: intialize**********************************/
$phpWord = new \PhpOffice\PhpWord\PhpWord();
/********************************************************/

/*********************step 3: add section***********************************/
$section = $phpWord->addSection();
/********************************************************/


/********step 4: intitialize font to apply to text**********************************/
$fontStyle = new \PhpOffice\PhpWord\Style\Font();
$fontStyle->setBold(true);
$fontStyle->setName('Bookman Old Style');
$fontStyle->setSize(14);
/********************************************************/


/*********************step 5: add text & apply font***********************************/
$myTextElement = $section->addText('Hello World');
$myTextElement->setFontStyle($fontStyle);
/********************************************************/

/*********************step 6: write file to drive***********************************/
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('helloWorld.docx');