#native_company# #native_desc#
#native_cta#

Creating MS Word documents on the fly Page 2

By Khairul Amri Yunus
on December 2, 2003

Substituting with the actual value

The following code opens the specified MS Word template document, substitutes
the value and saves it as a new file. We defined a Bookmark named “TODAYDATE”
in the document, which will be replaced with today’s date.

<?php

//1. Instanciate Word

$word = new COM("word.application") or die("Unable to instantiate Word");

//2. specify the MS Word template document (with Bookmark TODAYDATE inside)

$template_file "C:/reminder.doc";

//3. open the template document

$word->Documents->Open($template_file);

//4. get the current date MM/DD/YYYY

$current_date date("m/d/Y");

//5. get the bookmark and create a new MS Word Range (to enable text substitution)

$bookmarkname "TODAYDATE";

$objBookmark $word->ActiveDocument->Bookmarks($bookmarkname);

$range $objBookmark->Range;

//6. now substitute the bookmark with actual value

$range->Text $current_date;

//7. save the template as a new document (c:/reminder_new.doc)

$new_file "c:/reminder_new.doc";

$word->Documents[1]->SaveAs($new_file);

//8. free the object

$word->Quit();

$word->Release();

$word null;

?>



That’s it. Open the new document (c:/reminder_new.doc) and you will see today’s
date at the bookmark’s location.
  1. Initially we instantiated the Word object using this code:

    <?php

    $word 
    = new COM("word.application") or die("Unable to instanciate Word");

    ?>



  2. Then we specified the template document that contains the sample output and
    the Bookmark TODAYDATE:

    <?php

    $template_file 
    "C:/reminder.doc";

    ?>



  3. Next we opened the document:

    <?php

    $word
    ->Documents->Open($template_file);

    ?>



  4. Then we got today’s date using date() function. The Bookmark TODAYDATE will
    be replaced with this value:

    <?php

    $current_date 
    date("m/d/Y");

    ?>



  5. Next we found the Bookmark in the document and created a new MS Word Range.
    Range is used to perform text substitution or insertion.

    <?php

    $bookmarkname 
    "TODAYDATE";

    $objBookmark $word->ActiveDocument->Bookmarks($bookmarkname);

    $range $objBookmark->Range;

    ?>



  6. Then we substituted the bookmark with actual value:

    <?php

    $range
    ->Text $current_date;

    ?>



  7. Saved the template as a new document (c:/reminder_new.doc)

    <?php

    $new_file 
    "c:/reminder_new.doc";

    $word->Documents[1]->SaveAs($new_file);

    ?>



  8. Finally, we free the object:

    <?php

    $word
    ->Quit();

    $word->Release();

    $word null;

    ?>