Home Backend Development PHP Tutorial Tutorial on using PHP to generate Word documents under Windows system

Tutorial on using PHP to generate Word documents under Windows system

Jul 25, 2016 am 08:45 AM

Preparation

First, please ensure that a typical WAMP environment has been installed and configured on your Windows system. Since Interop is purely a Windows feature, we will build Apache and PHP under the Windows platform. In this example, I used EasyPHP 14.1, which is very easy to install and configure.

Next, we want to install Microsoft Office. The version is not strictly required. I'm using Office 2013 Professional, but any version of Office after 2007 should work.

We then need to make sure that the libraries for developing Interop applications (also known as PIA, Priority Interaction Components) are installed. To ensure this, we can open the explorer and find assembly. We will see the following installed PIAs branch:

201573144223171.png (1050×656)

We can see a Microsoft.Office.Interop.Word entry (underlined in this screenshot). This is the PIA we will be using in this example. Please pay special attention to its "name", "version" and "public key token". We are going to use them in our PHP script.

In this directory, we can also see other PIAs (including the entire Office family) used for programming (not only PHP, but also VB.net, C#, etc.).

If this list does not contain the entire package of Microsoft.Office.Interop, we can reinstall Office and include PIA in the installation; we can also manually download and install this package. Detailed installation steps can be found on this MSDN page.

Note: Only Microsoft Office 2010 PIA Redistributable can be downloaded and installed separately. The PIA version in this package is 14.0.0. Version 15 is only available by installing Office.

Finally, we need to enable the PHP extension php_com_dotnet.dll in the file php.ini and restart the server.

Now we can start programming.

HTML Form

Since this demo mainly focuses on backend processing, we use a simple HTML form to display the frontend. It should look like this:

201573144251848.png (889×757)

We have a text box for entering "Name", a radio button group for "Gender", a field value control for "Age" and a text field for writing "Message". Finally, we need a "Submit" button.

Name the file "index.html" and save it in the root directory of the virtual host so that we can access the file directly through the URL, for example: http://test/test/interop

Backstage

The backend PHP file is the core part we are going to discuss. I will post the code below first, and then explain it step by step

  1. $inputs = $_POST;
  2. $inputs['printdate']='';
  3. // A dummy value to avoid a PHP notice as we don't have "printdate" in the POST variables.
  4. $assembly = 'Microsoft.Office.Interop.Word, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c';
  5. $class = 'Microsoft.Office.Interop.Word.ApplicationClass';
  6. $w = new DOTNET($assembly, $class);
  7. $w->visible = true;
  8. $fn = __DIR__ . '\template.docx';
  9. $d = $w->Documents- >Open($fn);
  10. echo "Document opened.

    ";
  11. $flds = $d->Fields;
  12. $count = $flds->Count;
  13. echo "There are $count fields in this document.
    ";
  14. echo "
      ";
    • $mapping = setupfields();
    • foreach ($flds as $index => $f)
    • {
    • $f->Select();
    • $key = $mapping[$index];
    • $value = $inputs[$key];
    • if ($key == 'gender')
    • {
    • if ($value == 'm')
    • $value = 'Mr.';
    • else
    • $value = 'Ms.';
    • }
    • if($key=='printdate')
    • $value= date ('Y-m-d H: i:s');
    • $w->Selection->TypeText($value);
    • echo "
    • Mappig field $index: $key with value $value
    • ";
    • }
    • echo "
    ";
  15. echo "Mapping done!

    ";
  16. echo "Printing. Please wait...
    ";
  17. $d->PrintOut ();
  18. sleep(3);
  19. echo "Done!";
  20. $w->Quit(false);
  21. $w=null;
  22. function setupfields()
  23. {
  24. $mapping = array( );
  25. $mapping[0] = 'gender';
  26. $mapping[1] = 'name';
  27. $mapping[2] = 'age';
  28. $mapping[3] = 'msg';
  29. $mapping[ 4] = 'printdate';
  30. return $mapping;
  31. }
Copy code

After setting up the variable $inputs to get the value passed in the form, we need to create a dummy value to store the printdate - we will discuss why this variable is needed later - now, we see these 4 lines The more critical code:

  1. $assembly = 'Microsoft.Office.Interop.Word, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c';
  2. $class = 'Microsoft.Office.Interop.Word.ApplicationClass';
  3. $w = new DOTNET($assembly, $class);
  4. $w->visible = true;
Copy code

COM manipulation in PHP requires requesting an instance of a class in an assembly. In our case, we will be working with Word. If we take into account the code shown in our last screenshot, we will be able to construct a fully signed Word PIA:

  • "Name", "Version", and "Public Key Token" are the information displayed when we browse "c:Windowsassembly"
  • “Cultrue” is always neutral.


The suffix of the compiled file after calling the class is usually ApplicationClass.

By setting the following two steps, we can initialize a word object:

First of all, the word object can be saved in the background or displayed in the foreground by setting the visible attribute to true.

Then, we open the document to be processed and instantiate it as a $d variable.

In the document object, add the content of the document based on the text of the html form. Some parameters can be set here.
The worst way is to hardcode everything on the php page and then add them to the word object. I strongly recommend not to use this method for the following reasons:

1 The code is not flexible, any changes in the PHP content require re-modification of the script;
2 Violates the separation of control layer and display layer;
3. If you need to set the format of word content (alignment, font, style, etc.), this method greatly increases the number of lines of code, and it is very troublesome to modify the style programmatically.


Another way is to use "search-replace". This functionality built into PHP is very powerful. We can create a word document and place some separators around the placeholder content that needs to be replaced. For example, we create a document containing the following content:

  1. {{name}}
Copy code

In PHP, we simply replace with the "Name" value obtained from the form submission. This approach avoids the disadvantages of the first option. We just need to find the correct delimiter, and in this example, except that the template used is a word document, we are more like doing a template rendering.


The third option is my recommendation and is a premium theme in Word. We will use fields to represent placeholders, and in our PHP code, we will directly update the fields with the corresponding form values.

This method is flexible, fast, and conforms to Word’s best practices. This also avoids full-text searching of the file, which helps improve performance. Please note that this option has its drawbacks too.

In short, since its debut, Word has never supported named indexed fields. Although we provide a name for the fields we create in the Word document, we still use numeric subscripts to access each field. This also explains why we need to use a dedicated function (setupfields) to do the mapping manual between the field index and name of the form field


To learn how to insert fields into a Word document (click here to see a customized version), see related Word help topics and manuals. For this demo, we have a document with 5 MERGEFIELD fields. Additionally, we put the documentation and PHP scripts in one directory for easy access.

Please note that the printdate field does not have a corresponding form field. This is why we add a fake printdate as a key in the $inputs array. Without this key, the script can still be executed, but there will be a prompt indicating that the index printdate does not exist in the $inputs array.

After updating the field value using form data, we will print the document using the following command:

  1. $d->PrintOut();
Copy code

PrintOut method has several optional parameters, here, we use the simplest format. This will print a copy to the default printer linked to our Windows machine.


We can do print preview by using PrintPreview. In a purely automated scenario, of course, we use PrintOut directly for printing.

We also need to wait a moment before exiting the word application, because the printing job takes time to completely exit the background. Without delay(3), $w->Quit will be executed immediately and the printing job will be terminated immediately.

Finally, we call $w->Quit(false) to choose to close the word application via our PHP script call. The only parameter provided here is to indicate whether we want to save changes before exiting. We do make changes to the document, but we don't want to save them because we want to have a clean template for other users' input.

When we finish coding, we can load the form page, enter some content and submit the form. The screenshot below shows the output of the PHP script while updating the Word document:

201573144442664.png (889×757)

201573144502426.png (1663×843)

Increase coding speed and better understand PIA

PHP is a weakly typed language. A COM object is an Object type. In our PHP coding process, we cannot use the code auto-suggestion and completion function in an object, the same is true in a Word application, a document or even a field. We don't know what features it has, or what methods it supports.


This will significantly reduce the speed of our development. In order to make development faster, first of all, I suggest that the functions we develop in C# should be migrated to our PHP coding. I recommend a free C# IDE called "#develop", which you can download here. I prefer this software to VS because #develop is smaller, simpler, and more responsive.

Migrating C# code to PHP is not scary at all. Let me show you some C# code first:
Copy the code The code is as follows: Word.Application w=new Word.Application();
w.Visible=true;

String path=Application.StartupPath+"\template.docx";

Word.Document d=w.Documents.Open(path) as Word.Document;

Word.Fields flds=d.Fields;
int len=flds.Count;

foreach (Word.Field f in flds)
{
f.Select();
int i=f.Index;
w.Selection.TypeText("...");
}

We can see that the C# code is exactly the same as the PHP code base we showed before. Since C# is a strongly typed language, we can see some type conversion statements and we have to explicitly assign a type to our variables.

With code types, we can enjoy the automatic prompting and automatic code completion functions of the code, so that our development speed will be greatly improved.


Another way that can give us faster PHP development is to use Word macros. We first perform the actions we need to repeat, and then record them with a macro. A macro is actually Visual Basic and can also be translated into PHP very easily.

The most important thing is that the official Microsoft documentation of Office PIA, especially the namespace of each Office application in the document, will always be the reference we need most. The three most commonly used applications are as follows:

  • Excel 2013: http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel(v=office.15).aspx
  • Word 2013: http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word(v=office.15).aspx
  • PowerPoint2013: http://msdn.microsoft.com/en-us/library/microsoft.office.interop.powerpoint(v=office.15).aspx

Conclusion

In this article, we demonstrate how to use the PHP COM library and Microsoft Office Interop functionality to edit a Word document.

Windows and Office can be said to be widely used in our daily lives. Being able to know and understand the power of Office or Windows and PHP is very necessary for any programmer who develops PHP on the Windows platform.

Using PHP's COM extension, the door to mastering this combination is opened.

If you are interested in this part of programming, please leave your comment and we will consider writing more articles on this topic. I really look forward to more real-life application development using this approach.

Windows, PHP, Word


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

11 Best PHP URL Shortener Scripts (Free and Premium) 11 Best PHP URL Shortener Scripts (Free and Premium) Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram API Introduction to the Instagram API Mar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, React Build a React App With a Laravel Back End: Part 2, React Mar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation Survey Announcement of 2025 PHP Situation Survey Mar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles