PHP Generate Word Document from HTML

Kailash Singh

PHP Generate Word Document from HTML

Published Feb 03,2023 by Kailash Singh

0 Comment     1222 Views    


In this post, you will learn how to generate a word document in doc or docx using the PHP. 

Here is the complete code to generate and download a word document. So, mates use this code either on the localhost or on the server, only you will have to change the HTML of body content.

Source Code:

<?php
$file = 'elevensctech.doc';
header("Content-Type: application/force-download");
header( "Content-Disposition: attachment; filename=".basename($file));
header( "Content-Description: File Transfer");
@readfile($file);

$documentContent = '<html xmlns:v="urn:schemas-microsoft-com:vml" '
    .'xmlns:o="urn:schemas-microsoft-com:office:office" '
    .'xmlns:w="urn:schemas-microsoft-com:office:word" '
    .'xmlns:m="http://schemas.microsoft.com/office/2004/12/omml"= '
    .'xmlns="http://www.w3.org/TR/REC-html40">'
    .'<head><meta http-equiv="Content-Type" content="text/html; charset=Windows-1252">'
    .'<title></title>'
    .'<!--[if gte mso 9]>'
    .'<xml>'
    .'<w:WordDocument>'
    .'<w:View>Print'
    .'<w:Zoom>100'
    .'<w:DoNotOptimizeForBrowser/>'
    .'</w:WordDocument>'
    .'</xml>'
    .'<![endif]-->'
    .'<style>
    @page
    {
        font-family: Arial;
        size:215.9mm 279.4mm;  /* A4 */
        margin:14.2mm 17.5mm 14.2mm 16mm; /* Margins: 2.5 cm on each side */
    }
    h2 { font-family: Arial; font-size: 18px; text-align:center; }
    p.para {font-family: Arial; font-size: 13.5px; text-align: justify;}
    </style>'
    .'</head>'
    .'<body>'
    .'<h2>Welcome To Elevenstech Web Tutorials</h2><br/>'
    .'<p class="para">'
    .'Elevenstech Web Tutorials helps you learn coding skills and enhance your skills you want.
    As part of Elevenstech\'s Blog, Elevenstech Web Tutorials contributes to our mission of "helping people learn coding online."'
    .'</p>' 
    .'</body>' 
    .'</html>'; 
echo $documentContent; 
?> 

 


Comments ( 0 )