Create MS Word Document in PHP

Introduction

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.

Example

<?php

//header part

header("Content-type: application/vinod.ms-word");

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>";

?>

Output 

For opening and saving a document:

mysqli1.jpg

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

mysqli2.jpg

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

<?php

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

$doc->Visible =0;

$doc->document->Add();

// 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

$doc->selection->typeText("TEXT!");

// Save the doc file

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

$doc->document[1]->SaveAs($f_name);

$doc->quit();

unset($doc);

header("Content-type: application/vinod.ms-word");

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

readfile($f_name);

unlink($f_name);

?>

 

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

Example 2

<?php

$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";

    $rowcount++;    

    $rs->MoveNext();

}

$rs->Close();

$con->Close();

$rs = null;

$con = null;

?>

Up Next
    Ebook Download
    View all
    Learn
    View all