Create word file in PHP

Asked

Viewed 1,764 times

0

I have a docx file, model of a contract. In it, the buyer’s data and other data are variable. The PHP system needs to get database information and replace in the model docx file. That is, maintain the main structure and replace only a few words. After, save the word and make available for download.

I have seen some libraries that do this, where you can define variables and make these substitutions. However, I don’t remember the name nor how to do.

Someone who could help me? With resources I can use and/or small examples?

Example: The document has a fixed paragraph. In this paragraph, a variable word will be defined at the time of generating the file and after customizing the template, it should be saved in docx.

  • 1

    I haven’t read it all, but here’s what helps: https://stackoverflow.com/questions/9891712/opentbs-mail-merging-docx-using-php

  • That’s exactly what it was! Thank you so much!

1 answer

1


Use the PHPOffice/PHPWord, it is necessary to use composer, read about this:

  • Then in the project folder run:

    Composer require phpoffice/phpword

Then in your file you will run:

<?php

require_once '../vendor/autoload.php';

$phpWord = new \PhpOffice\PhpWord\PhpWord();

// Adiciona sessão com texto
$section = $phpWord->addSection();
$section->addText('Foo bar baz, etc etc etc 1');

$section->addText('Foo bar baz, etc etc etc 2', array(
    'name' => 'Tahoma',
    'size' => 10
));

// Adiciona texto com fonte customizada
$fontStyleName = 'oneUserDefinedStyle';
$phpWord->addFontStyle(
    $fontStyleName,
    array('name' => 'Tahoma', 'size' => 10, 'color' => '1B2232', 'bold' => true)
);

$section->addText('Teste test', $fontStyleName);

// Texto com fonte diferente
$fontStyle = new \PhpOffice\PhpWord\Style\Font();
$fontStyle->setBold(true);
$fontStyle->setName('Tahoma');
$fontStyle->setSize(13);
$myTextElement = $section->addText('Foo Bar Baz');
$myTextElement->setFontStyle($fontStyle);

// Saving the document as OOXML file...
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');

//Local para salvar o documento
$objWriter->save('exemplo.docx');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.