PHP Simple Word Document Example

How to create a simple Microsoft Word document with PHP only

PHP Create Simple Word Document ExampleI’ve had the need to create several word documents over the years for various clients and found the simplest way to do it without having to install specific libraries or third party software is to just create the document with plain PHP.

The following script will create a word document named document_name.doc. When you browse to the page with this script the page will automatically prompt you to open or save the file.

How to create a simple word document using PHP.

<?php 

// setup for word

    header("Content-Type: application/vnd.ms-word");
    header("Content-Disposition: attachment; filename=document_name.doc");

// produce document

    echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
    echo "<html xmlns=\"https://www.w3.org/1999/xhtml\">";
    
    echo "<html>";
    echo "<head>";
    echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
    echo "<style type='text/css'>";
    echo "@page Section1
    {
        size:8.5in 11.0in;
        margin:.5in .5in .5in .5in;
        mso-header-margin:.5in;
        mso-footer-margin:.5in;
        mso-paper-source:0;
        font-family:Arial;
        font-size:8pt;
        mso-font-charset:0;
        mso-generic-font-family:auto;
    }
    td{
        font-family:Arial;
        font-size:8pt;
        mso-font-charset:0;
        mso-generic-font-family:auto;
    }
    div.Section1
    {
        page:Section1;
    } ";
    echo "</style>";
    echo "</head>";
    
    echo "<body>";
    echo "<div class='Section1'>";

    echo "<p>This is where your content will display</p>";

    echo "</div>";
    echo "</body>";
    echo "</html>";

?>

Copy Code

References

PHP echo
PHP header

 


Leave a Reply

I appreciate and welcome your comments. Please keep in mind that comments are moderated according to my comment policy.
Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.