How to Write to a Word Document Using PHP File Functions

104 14

Instructions

Write to a Word Document Using a COM Object

1

Create a new Word COM object. For example, type:

<?php

$word_doc = new COM("word.application");
2

Hide the window until you have populated your document. For example, type:

$word_doc->Visible = 0;
3

Add a new Word document to the object. For example, type:

$word_doc->Documents->Add();
4

Create the text to go into the Word document and format it appropriately. For example, type:

$word_doc->Selection->Font->Name = "Times New Roman";

$word_doc->Selection->Font-Size = "12";

$word_doc->Selection->TypeText("My Thesis");
5

Set the document margins. For example, type:

$word_doc->Selection->PageSetup->LeftMargin = "1";

$word_doc->Selection->PageSetup->RightMargin = "1";

$word_doc->Selection->PageSetup->TopMargin = "1";

$word_doc->Selection->PageSetup->BottomMargin = "1";
6

Save the document. For example, type:

$file = "myfile.docx";

$word_doc->Documents[1]->SaveAs($file);
7

Quit the document and free the COM object. For example, type:

$word_doc->quit();

unset($word_doc);

?>

Create Word Document Using PHPWord

1

Download the PHPWord library from the Microsoft CodePlex site and place it on your server. Include the library at the beginning of the PHP script. For example, type:

<?php

include("PHPWord.php");
2

Create a new PHPWord object and add a new section to the document For example, type:

$word = new PHPWord();

$s = $word->createSection();
3

Add your text to the section. For example, type:

$s->addText("My Thesis");
4

Format text by passing an array as the second parameter to the addText method. For example, type:

$s->addText("Thesis Objective", array("name"=>"Arial", "size"=>"14", "bold"=>true));
5

Save the document. For example, type:

$obj = PHPWord_IOFactory::createWriter($word, "Word2007");

$obj->save("mythesis.docx");

?>
Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.