PHP HTML

HOW TO CONVERT HTML TO DOCX IN PHP

(quick guide & example)

Open the command line, navigate to your project folder, enter composer require phpoffice/phpword.

Composer will automatically download the latest version into the vendor/ folder.

DOWNLOAD PHPWORD

01

LOAD PHPWORD require "vendor/autoload.php"; $pw = new \PhpOffice\PhpWord\PhpWord();

HTML TO DOCX (A)

02

HTML CONTENT $html = "<h1>HELLO WORLD!</h1>"; $html .= "<p>Paragraph</p>";

ADD SECTION + PLACE HTML $section = $pw->addSection(); \PhpOffice\PhpWord\Shared\Html:: addHtml($section, $html, false, false);

SAVE TO DOCX ON SERVER $pw->save("demo.docx", "Word2007");

HTML TO DOCX (B)

03

OR FORCE DOWNLOAD header("Content-Type:application/ octet-stream"); header("Content-Disposition: attachment;filename=\"demo.docx\"");

$objWriter = \PhpOffice\PhpWord\ IOFactory::createWriter($pw, "Word2007"); $objWriter->save("php://output");