发信人: jackyz()
整理人: dalasthunder(2002-07-25 06:17:51), 站内信件
|
COM Functions in PHP4 (Windows)
Alain M. Samoun
Introduction
The built-in COM functionality of PHP4 is quite attractive for some of us programming in the win32 environment. So far, there is not much do cumentation on the subject. This short article will explain how to use COM in real PHP4 programming with three examples using MS office 2000 Word and Excel programs and the Adobe Distiller program. The COM tech nology has been developed by Microsoft for several years, under differ ent names. As far as this article is concerned, the words OLE, OLE Aut omation, ActiveX and COM are all the same: They designate an encapsula ted piece of code (the Object) that performs some functions for a wind ows application. PHP4 COM connects to the object (Instantiate the obje ct) and uses its methods and properties.
If you want to reproduce the following examples, here is my configurat ion:
Windows 98 - MS Office 2000
Apache 1.3.9 Windows
PHP4.02 Dev (08-20-00) Running as CGI
COM tags in PHP4
Lets start with the specific information to use the COM functions with PHP4. To instantiate a component, one needs the "new" operator and th e "OLE programmatic identifiers" of the object:
<?php
$instance = new COM("$identifier");
?>
Since COM is a reserved class name in PHP4, it passes the object's ide ntifier to the constructor. Now that we have instantiated the componen t, we can easily reach its methods and properties, using the OOP class . For example:
<?php
$instance->[Object]->[method1]->[method2]->..->[property];
?>
It's that simple!
There are two tag functions for PHP4 COM that are used when the OOP co nstruct doesn't work. (In the case of PHP syntax problems, with the na mes and values of properties with invalid characters, like dot or pare nthesis):
<?php
bool com_set(class com_object, string property name, string property_v alue);
mixed com_get(class com_object, string property_name);
?>
Finally, PHP4 also supports DCOM to create an instance of an object on a remote computer:
<?php
$Instance = new COM(string "Component name", string "remote_server_add ress");
?>
Note: there is a DCOM directive to set in the PHP configuration. PHP d evelopers may add DCOM support for Unix in the future. That's all, the re are no other functions to remember!
Identifiers, methods and properties.
identifiers are strings like:
For MS Word: "Word.Application" or "Word.Application.9"
MS Excel: "Excel.Application" or "Excel.Sheet"
ADOBE Acrobat: "Exch.application" or "PdfDistiller.PdfDistiller"
As the last identifier name indicates, it is not always easy to know t he right name for the object. If you do not have access to a VBA doc, you can look at the windows registry (Start - Run regedit) and look in the HKEY_CLASSES_ROOT folder: Scan down until the end of the extensio ns list, you will then reach the Application names. The COM Identifier s available in your machine, are the folders with the CLSID subfolders .
The application program should document its COM methods and properties . In the case of Office 2000, start the application, then open the vis ual basic editor with the <ALT+F11> short cut key and select the Objec ts Editor <F2>. Enter a name of method or properties for the applicati on's library. Then, select a class or member and right click on the me mber name in the next window below. You will get the description for t he class or member by selecting help. You can also consult MSDN. An ex ample for Excel is: http://msdn.microsoft.com/library/officedev/off200 0/xltocobjectmodelapplication.htm
Using PHP4 COM functions with MS Word
Now, we have all we need to start with the first code example:
<?php
#*********************************************************
# This example, slightly modified from the Zend site,
# will open an instance of word with a new
# document with the name "Useless test.doc" and the line:
# "This is a test2..." typed inside.
#*********************************************************
#Instantiate the Word component.
$word = new COM("word.application") or die("Unable to instantiate Word ");
#Get and print its version
print "Loaded Word, version {$word->Version}<BR>";
#Another way to get the version using com_get
$testversion = com_get($word->application,version);
print "Version using Com_get(): $testversion <BR>";
#Make it visible in a window
$word->Visible = 1;
#Open a new document
$word->Documents->Add();
#Write something
$word->Selection->TypeText("This is a test...");
#Now save the document
$word->Documents[1]->SaveAs("Useless test.doc");
#Comment next line if you want to see the word document,
#then close word manually
$word->Quit();
#Comment if you want to see the word document, then close
?>
If you study this example for a few minutes using the OLE documentatio n that comes with Word, you will learn practically all you need to wri te your own program.
Using the PHP4 COM functions with MS Excel
As for the Word example above, study the code with the help from the V isual Basic Editor ObjectBrowser for Excel.
<?php
#Set the workbook to use and its sheet. In this example we use a sprea dsheet that
#comes with the Excel installation called: SOLVSAMP.XLS
$workbook = "C:\Program Files\Microsoft office\Office\Samples\SOLVSAMP .XLS";
$sheet = "Quick Tour";
#Instantiate the spreadsheet component.
$ex = new COM("Excel.sheet") or Die ("Did not connect");
#Get the application name and version
print "Application name:{$ex->Application->value}<BR>" ;
print "Loaded version: {$ex->Application->version}<BR>";
#Open the workbook that we want to use.
$wkb = $ex->application->Workbooks->Open($workbook) or Die ("Did n ot open");
#Create a copy of the workbook, so the original workbook will be prese rved.
$ex->Application->ActiveWorkbook->SaveAs("Ourtest");
#$ex->Application->Visible = 1; #Uncomment to make Excel visible.
# Read and write to a cell in the new sheet
# We want to read the cell E11 (Advertising in the 4th. Quarter)
$sheets = $wkb->Worksheets($sheet); #Select the sheet
$sheets->activate; #Activate it
$cell = $sheets->Cells(11,5) ; #Select the cell (Row Column num ber)
$cell->activate; #Activate the cell
print "Old Value = {$cell->value} <BR>"; #Print the value of th e cell:10000
$cell->value = 15000; #Change it to 15000
print "New value = {$cell->value}<BR> ";#Print the new value=15000
#Eventually, recalculate the sheet with the new value.
$sheets->Calculate; #Necessary only if calc. option is manual
#And see the effect on total cost(Cell E13)
$cell = $sheets->Cells(13,5) ; #Select the cell (Row Column num ber)
$number = Number_format($cell->value);
print "New Total cost =\$$number - was \$47,732 before.<BR>";
#Should print $57,809 because the advertising affects the Corporate ov erhead in the
# cell formula.
#Example of use of the built-in functions in Excel:
#Function: PMT(percent/12 months,Number of payments,Loan amount)
$pay = $ex->application->pmt(0.08/12,10,10000);
$pay = sprintf("%.2f",$pay);
print "Monthly payment for $10,000 loan @8% interest /10 month s: \$ $pay<BR>";
#Should print monthly payment = $ -1,037.03
#Optionally, save the modified workbook
$ex->Application->ActiveWorkbook->SaveAs("Ourtest");
#Close all workbooks without questioning
$ex->application->ActiveWorkbook->Close("False");
unset ($ex);
?>
This example should get you going with the Excel COM and PHP. Of cours e there are many more objects to use. Writing an OOP wrapper for the p rincipal functions will make access to the excel objects even easier.
Using PHP COM with Adobe Distiller
This last example is for a non-MS program: If your program has produce d a PostScript document, it may be interesting to transform it (Distil l it) to a PDF document. Adobe has a program called Distiller with a w indows version that can be instantiated, with the following code:
<?php
$pdf = new COM("pdfdistiller.pdfdistiller.1");
?>
Note that the OLE Identifier name is not obvious, especially when the distiller documentation (Adobe's Technical Note #5158) refers to it as "pdfdistiller."
The principal method to distill a document is:
<?php
$pdf->FileToPdf ($psfile, strOutputPDF '', strJobOptions "");
?>
Where $psfile is the name of the PostScript file, strOutputPDF is the name for the output PDF file. StrJobOptions is the name of the paramet ers file for Distiller. The two last parameters of the method can be l eft blank to use the same name, the PS file for the PDF file and to us e the default Job options file. For example:
<?php
$pdf->FileToPdf ($psfile, "", "");
#Where $psfile could be Myfile.ps and the result file: Myfile.pdf
?>
There are more methods and properties that can be used with Distiller. If you are interested, look at the Adobe's technical note.
Caveats/Possible problems
If there are some errors in your code, you may instantiate the object and your program may not close before it times out. Worst of all, the application may retentively be instantiated. As a result, several copi es may lay around in your programs list and interfere after you have c orrected the problem. The solution: After fixing the bug, clean up (<C TRL+ALT+Delete> and End Task) all the instances in the program list be fore you restart. For this same reason, always close the application a t the end of your code and unlink the instance.
You may experience some oddities with com_get and com_set. For example : $Version = Com_get($instance->Application,"Version"); Works with Word, but p roduces an error with Excel.
Some Objects won't be instantiated by PHP4, it appears that these obje cts need a custom interface that PHP4-COM doesn't support.
Why use it?
Hopefully, these three examples have shown you the ropes. PHP COM allo ws the connection to many Windows programs inside a PHP script. The co de is simpler than ASP's and can be integrated with the rest of PHP's powerful database functions. Microsoft markets the COM technology ever ywhere and under different names and architectures, like COM+(Combine COM with Microsoft Transaction Server MTS), ADO, OLE DB, OWC, Windows DNA, etc. PHP and Apache, working together, are now offering an open s ource solution to this confusion.
http://phpclasses.upperdesign.com/browse.html?package=86
--Alain
PS: See the EXCEL class using the COM interface at:
-----------------------------------------------------------------
看不惯羊文的朋友写信给 limodou 让他给翻译翻译啦.哈哈.
-- ※ 来源:.月光软件站 http://www.moon-soft.com.[FROM: 61.141.206.125]
|
|