Create MS Word Document in PHP


In this article I explain how to create a Word document file by PHP. A document file is created using HTTP headers. This is very simple and useful in PHP when the user opens a PHP application in a Word document then you can use that and easily create a document file using PHP but this file is not a pure document file but certainly it can be opened in a document application.



//header part

header("Content-type: application/");

header("Content-Disposition: attachment;Filename=MCN.doc");

//starting html tag

echo "<html>";

echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";

//body part start here

echo "<body>";

//print the content

echo "<b>This is my first document created by PHP</b>";

echo "</body>";

//end html tag

echo "</html>";



For opening and saving a document:


 This document file you can only read, not write, the file.


In the next example I will explain a document file with a COM object. Here COM only works in Windows and COM functions are only available for the Windows version of PHP. First a Word document is saved then is sent the browser to be read. In this example I will use the "sys_get_temp_dir()" function; this function returns a directory path used for a temp directory.

Example 1


$doc = new Com("word.application");

$doc->Visible =0;


// set here page margins

$doc->selection->pageSetup->leftMargin = '2';

$doc->selection->pageSetup->rightMargin = '2';

//settings your font

$doc->selection->font->name = 'Arial';

$doc->selection->font->size = 10;

// here add text


// Save the doc file

$f_name = tempnam(sys_get_temp_dir(), "word");




header("Content-type: application/");

header("Content-Disposition: attachment;Filename=MCN.doc");





In the next example I will explain with a database. Such as:

Example 2


$con = new COM("ADODB.Connection") or die("Cannot start ADO");

$con->Open("Provider=SQLOLEDB; Data Source=localhost;

Initial Catalog=database; Username=root; Password=");

$rs = $con->Execute("SELECT * FROM courses");

$num_columns = $rs->Fields->Count();

echo $num_columns . "\n";

for ($i=0; $i < $num_columns; $i++) {

    $fld[$i] = $rs->Fields($i);


$rowcount = 0;

while (!$rs->EOF) {

    for ($i=0; $i < $num_columns; $i++) {

        echo $fld[$i]->value . "\t";


    echo "\n";






$rs = null;

$con = null;