How to generate word document in PHP?

by beatrice.lesch , in category: PHP , 2 years ago

How to generate word document in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@beatrice.lesch You can use PHPWord library to generate Word document with PHP, here is code as example:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<?php

// Creating the new document...
$word = new \PhpOffice\PhpWord\PhpWord();

// Adding an empty Section to the document...
$section = $word->addSection();
// Adding Text element to the Section having font styled by default...
$section->addText(
    'Some text'
);

// Adding Text element with font customized inline...
$section->addText(
    'One more text',
    array('name' => 'Tahoma', 'size' => 10)
);

// Saving the document as OOXML file...
$writer = \PhpOffice\PhpWord\IOFactory::createWriter($word, 'Word2007');
$writer->save('example.docx');


by audrey.hodkiewicz , a year ago

@beatrice.lesch 

To generate Word documents in PHP, you can use the PHPWord library, which provides a simple way to create and modify Word documents in PHP. Here are the steps:

  1. Install the PHPWord library using composer. Run the following command from your command line: composer require phpoffice/phpword
  2. Create a new PHP file and include the PHPWord autoloader: require_once 'vendor/autoload.php';
  3. Create a new PHPWord object: $phpWord = new PhpOfficePhpWordPhpWord();
  4. Add a new section to the document: $section = $phpWord->addSection();
  5. Add some text to the section: $section->addText('Hello World!');
  6. Save the document as a Word document: $writer = PhpOfficePhpWordIOFactory::createWriter($phpWord, 'Word2007'); $writer->save('hello_world.docx');


This will create a new Word document named "hello_world.docx" with the text "Hello World!". You can modify the document by adding more sections, tables, images, or other elements. The PHPWord library provides a wide range of features to create and modify Word documents, so check out the documentation for more details.