search
HomeBackend DevelopmentPHP TutorialTutorial on using PHP to generate Word documents under Windows system

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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.