1. Go to this page and download the library: Download dskripchenko/php-docx library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
dskripchenko / php-docx example snippets
use Dskripchenko\PhpDocx\Html\Converter;
use Dskripchenko\PhpDocx\Writer\Word2007Writer;
$html = <<<HTML
<h1>Invoice #42</h1>
<p>Total: <strong>500 USD</strong></p>
<table>
<tr><th>Item</th><th>Qty</th></tr>
<tr><td>Widget</td><td>2</td></tr>
</table>
<p>Page <page-number/> of <page-total/></p>
HTML;
$doc = (new Converter)->fromHtml($html);
file_put_contents('invoice.docx', (new Word2007Writer)->write($doc));
use Dskripchenko\PhpDocx\Reader\DocxReader;
use Dskripchenko\PhpDocx\Reader\DocxPackageReader;
use Dskripchenko\PhpDocx\Reader\VariableDetector;
use Dskripchenko\PhpDocx\Html\Serializer;
$bytes = file_get_contents('input.docx');
$document = (new DocxReader)->read($bytes);
$pkg = (new DocxPackageReader)->read($bytes);
$variables = (new VariableDetector)->detect($pkg);
$imported = (new Serializer)->serialize($document, $variables);
echo $imported->bodyHtml;
echo $imported->headerHtml;
echo $imported->footerHtml;
echo $imported->watermarkText;
$imported->pageSettings;
$imported->variables;
$imported->media;
use Dskripchenko\PhpDocx\Style\StyleRegistry;
use Dskripchenko\PhpDocx\Style\RunStyle;
use Dskripchenko\PhpDocx\Style\ParagraphStyle;
use Dskripchenko\PhpDocx\Style\Alignment;
$styles = (new StyleRegistry)
->heading(1, new RunStyle(sizeHalfPoints: 44, bold: true), new ParagraphStyle(alignment: Alignment::Center))
->heading(2, new RunStyle(sizeHalfPoints: 28, bold: true));
$writer = new Word2007Writer($styles);
use Dskripchenko\PhpDocx\Build\DocumentBuilder;
use Dskripchenko\PhpDocx\Style\PageSetup;
use Dskripchenko\PhpDocx\Style\PaperSize;
use Dskripchenko\PhpDocx\Style\Orientation;
$doc = DocumentBuilder::new()
->pageSetup(new PageSetup(
paperSize: PaperSize::A4,
orientation: Orientation::Portrait,
))
->watermark('CONFIDENTIAL')
->heading(1, 'Report')
->paragraph('Body')
->build(); // → Document AST
$bytes = DocumentBuilder::new()->paragraph('Hi')->toBytes();
$count = DocumentBuilder::new()->paragraph('Hi')->toFile('out.docx');