Tutorial on using PHP to generate Word documents under Windows system _php tips

Source: Internet
Author: User
Tags dotnet html form php script

Preparatory work

First, make sure that a typical WAMP environment is installed and configured in your Windows system. Because interop is purely a feature of Windows, we will build Apache and PHP under the Windows platform. In this example, I used easyphp 14.1, which is easy to install and configure.

Next, we will install Microsoft Office. Versions are not strictly required. I am using the Office2013 Professional Edition, but any Office version after 2007 should be available.

We then need to make sure that the libraries that develop interop applications (also known as PIA, priority interaction) are installed. To ensure this, we can open the resource manager and then find the <windows directory >\assembly, and we'll see the PIAs branch installed below:

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

In this directory, we can also see other PIAs (including the entire Office family) for programming (not just PHP, but also vb.net, C #, and so on).

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

Note: Only the Microsoft Office PIA Redistributable can be downloaded separately for installation. The PIA version in this package is 14.0.0. Version 15 can only be obtained by installing Office.

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

Now we can start programming.

HTML form

Because this demo is mainly concerned with the processing of the background, so we use a simple HTML form to do the front of the show, it should look like this:

We have a text box for entering "Name", a "Gender" radio button Group, a "age" field value control and a text field to write "message", and finally, a "Submit" button is required.

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

Background

The PHP file backstage is the core part of our discussion. I'll just post the code below and explain it step-by-step.

<?php $inputs = $_post; 
$inputs [' printdate ']= '; 
 
A dummy value to avoid a PHP notice as we don ' t have "printdate" in the POST variables.
$assembly = ' Microsoft.Office.Interop.Word, version=15.0.0.0, culture=neutral, publickeytoken=71e9bce111e9429c ';
 
$class = ' Microsoft.Office.Interop.Word.ApplicationClass ';
$w = new Dotnet ($assembly, $class);
 
$w->visible = true; $FN = __dir__.
 
' \\template.docx ';
 
$d = $w->documents->open ($FN);
 
echo "Document opened.<br> 

After setting the variable $inputs to get the values passed in the form, we're going to create a dummy value to store printdate--we'll talk about why we need this variable later--now we see the 4 lines of code that are more critical:

$assembly = ' Microsoft.Office.Interop.Word, version=15.0.0.0, culture=neutral, publickeytoken=71e9bce111e9429c ';
$class = ' Microsoft.Office.Interop.Word.ApplicationClass ';
 
$w = new Dotnet ($assembly, $class);
$w->visible = true;

COM manipulations in PHP need to request an instance of class in a assembly. In our case, I see that I will be working with Word. If you take into account the code shown in our previous screenshot, we will be able to construct a fully signed word PIA:

    • "Name", "Version", "Public Key Token" is the information displayed when we browse "c:\Windows\assembly"
    • "Cultrue" is always neutrual.


The file suffix called the class is compiled with the name usually ApplicationClass.

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

First, the Word object can be saved in the background or displayed in the foreground by setting the Visible property to True.

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

In the Document object, you add the contents of the document based on the text of the HTML form, where you can set some parameters.
The worst way to do this is to hard-code everything on the PHP page and add them to the Word object. I strongly recommend that such a method not be adopted because:

1 code is not flexible, any changes in PHP content will need to modify the script;
2 violation of the control layer, the separation of the display layer;
3 If you need to format Word content (alignment, font, style, etc.), this way greatly increases the number of lines of code, and programmatically modify the style is very cumbersome.


Another way is to use search-replace. This is a powerful feature built into PHP. We can create a Word document and place some delimiters around the placeholder that needs to be replaced. For example, we create a document that contains the following:

{{Name}}

In PHP, we simply replace it with the "Name" value obtained from the form submission. This approach avoids the drawbacks of the first option. We just need to find the right separator, in this case, in addition to using the template is a Word document, we are more like a template rendering.


The third option is my recommendation and is an advanced topic in Word. We'll use fields to represent placeholders, and in our PHP code we'll update the fields of the corresponding form values directly.

This approach is flexible, fast, and conforms to Word's best practices. This also avoids full-text searches for files, which can help improve performance. Please note that this option has its drawbacks.

In short, since the first appearance, Word has never supported a named index field. Although we provide a name for the fields that we create in the Word document, we still have to use a digital subscript to access each field. This also explains why we use specialized functions (setupfields) To do field indices for form fields and mapping manuals between names


Learn how to insert a field in 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. In addition, we put the documents and PHP scripts in a directory for easy access.

Note that the PrintDate field does not have a corresponding form field. That's why we're adding a fake printdate as a key in the $inputs array. Without this key, the script can still execute, but there is a hint that the index printdate does not exist in the $inputs array.

After you use the form data to update the values of the fields, we will print the document using the following command:

$d->printout ();

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


We can print a preview by using PrintPreview. In a purely automated scenario, of course, we print directly using printout.

Before exiting the Word application, we still need to wait a little longer because the print job takes time to completely exit the background. If there is no delay (3), the $w->quit will be executed immediately and the print work is terminated immediately.

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

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

Improved coding speed and better understanding of PIA

PHP is a weak type of language. A COM object is an object type. In our PHP coding process, we can't use code auto prompt and completion in one object, 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 greatly reduce the speed of our development. To make development faster, first of all, I recommend that we develop features in C # that should be migrated to our PHP code. I recommend a free C # IDE called "#develop," which you can download here. Compared to VS, I prefer this software because the #develop is smaller, simpler and faster to respond to.

C # code migration to PHP is not scary at all. Let me first show some C # code:

Copy Code code 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 ("...");
}

As we can see, C # 's code is exactly the same as the PHP code we presented earlier. Since C # is a strongly typed language, we can see some types of conversion statements, and we have to explicitly assign a type to our variables.

With the type of code, we can enjoy the code automatically prompts and code completion function, so that we develop the speed will be greatly improved.


Another way to give us a faster pace of PHP development is to use Word's macro commands. Let's start with the action we need to repeat, and then record it with a macro. A macro is actually visual Basic and can also be easily translated into PHP.

Most importantly, office PIA Microsoft Official documents, especially the namespaces in the documentation for each Office application, are always the most wanted references we need. The more commonly used 3 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 demonstrated how to use the PHP COM library and Microsoft Office Interop features to make a Word document.

Windows and office can be said to be widely used in our daily life. The ability to know and understand the strengths of office or Windows, as well as PHP, is essential for any programmer who develops PHP on a Windows platform.

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

If you are interested in this part of programming, please leave a comment and we will consider writing more articles on this topic. I am looking forward to more real-life application development that can be used in this way.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.