COM functions in PHP4 (windows version)_PHP tutorial
COM functions in PHP4 (windows version)
I have been writing about converting excel into mysql these days, and I found an article. I searched the phpx forum, but there was no such post. I reposted it as follows:
COM function in PHP4 (windows version)
Introduction
The COM functions built into PHP4 are quite attractive for us to develop programs in the win32 environment, but there are still not many relevant technical documents. This article will use three examples to illustrate how to use COM functions in PHP, dealing with MS office 2000 Word, Excel, and Adobe Distiller respectively.
COM technology was proposed and developed by Microsoft a few years ago. The related terms mentioned in this article are OLE, OLE Automation, ActiveX, COM. The meanings of these words are basically the same
Like this, they all mean using a piece of encapsulated code (object) to complete some functions of a windows application. PHP4 COM functions can connect to an object instance and use its methods and
properties.
If you want to use the example source code below, please refer to my configuration.
Windows 98 - MS Office 2000
Apache 1.3.9 Windows
PHP4.02 Dev (08-20-00) Running as CGI
COM in PHP4 Tags
Now let’s start using PHP4’s COM to instantiate a component. You need the new operator and the object’s "OLE Program Identifier":
$instance = new COM ("$identifier");
?>
Because COM is a reserved word of PHP4, it passes the identifier of this object to a constructor, and now an instance of this component is obtained , according to the nature of the OOP class, we can easily access its methods and properties
.
For example:
$instance->[Object]->[method1]->[method2]->..->[property];
?>
It’s that simple!
The OOP structure cannot work under PHP (due to PHP syntax problems, the name and value of the attribute are illegal characters, such as dots and parentheses, etc.), so PHP4 provides two corresponding functions:
bool com_set(class com_object, string property name, string property_value);
mixed com_get(class com_object, string property_name);
?>
Finally, PHP4 also supports DCOM technology, which can create an object instance on a remote computer.
$Instance = new COM(string "Component name", string "remote_server_address");
?>
Note: This is using DCOM instructions Set up PHP. In the future, PHP developers will provide support for DCOM under Unix.
Identifiers, methods and properties
Identifier is a string as follows:
MS Word: "Word.Application" or "Word.Application.9"
MS Excel: "Excel.Application" or "Excel.Sheet"
ADOBE Acrobat: "Exch.application" or "PdfDistiller.PdfDistiller"
For the last identifier, I want to specify that, get the correct Object identification names are not an easy task. If you don't have access to the VBA documentation, you can look up the Windows registration
table and look for it in HKEY_CLASSES_ROOT, and you can get the names of some applications. The object IDs valid on your machine are placed in the CLSID subfolder.
Applications generally provide documentation describing its COM methods and properties. In office2000, you can run the program, open the VBA editor, and select the object editor. Enter a method name or attribute name in the application
library, then right-click a class or member name in the window below, click Help, and you will get a description of the class or member . You can also
refer to MSDN. An Excel example is as follows: [url]http://msdn.microsoft.com/library/officedev/off2000/xltocobjectmodelapplication.htm[/url]
Use COM functions to operate MS Word
Now, let’s start with our first example:
#**************************** ****************************
# This example is from the Zend site, with slight modifications
# Open a word instance, and create a new document Useless test.doc
# Enter a line of text "This is a test2..."
#******************** ***********************************
#Instantiate an object
$word = new COM("word.application") or die("Unable to instantiate Word");
#Get and display the version
print "Loaded Word, version {$word->Version}
";
#Another way to get the version
$testversion = com_get($word->application,version);
print "Version using Com_get(): $testversion
";
#Make it visible
$word->Visible = 1;
#Create new document
$word->Documents->Add();
#Write characters
$word->Selection->TypeText(" This is a test...");
#Save
$word->Documents[1]->SaveAs("Useless test.doc");
#Close
$word->Quit();
?>
You only need to spend a few minutes to read this program and refer to Word's OLE technology Documentation, you will learn almost all the operations you need in your own programs.
MS Excel using PHP's COM function
Just like the Word example above, you should refer to the help documentation of the object browser in Excel's Visual Basic editor while studying this example. .
#Open the workbook and its sheet,
#This example uses a spreadsheet which is SOLVSAMP.XLS that comes with Excel installation
$workbook = "C:Program FilesMicrosoft officeOfficeSamplesSOLVSAMP. not connect");
#Get the program name and version
print "Application name:{$ex->Application->value}
";
print "Loaded version: {$ex->Application->version}
";
#Open the workbook so we can use it
$wkb = $ex->application->Workbooks-> ;Open($workbook) or Die ("Did not open");
#Presave the original workbook and create a copy of the workbook
$ex->Application->ActiveWorkbook ->SaveAs("Ourtest");
#$ex->Application->Visible = 1; #Comment this sentence to make Excel visible
# Read and write a cell in a new
# We can read this 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 number)
$cell->activate; #Activate the cell
print "Old Value = {$cell->value}
"; #Print the value of the cell:10000
$cell->value = 15000; #Change it to 15000
print "New value = {$cell->value}
";#Print the new value=15000
#Finally, recalculate the cell with the new value
$sheets->Calculate ;
#Required if you want to calculate, manual is optional
#You can see the total value of the effect (cell E13)
$cell = $sheets->Cells(13,5); #Select the cell (Row Column number)
$number = Number_format($cell->value);
print "New Total cost =$$number - was $47,732 before.
";
#According to the calculation formula, advertising affects the company's expenses, which will be displayed here is $57,809
#Use Excel's built-in 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 months: $ $pay
";
#Should print monthly payment = $ -1,037.03
#Optional, save
$ex-> ;Application->ActiveWorkbook->SaveAs("Ourtest");
#Close, no questions
$ex->application->ActiveWorkbook->Close("False");
unset ($ex);
?>
This example allows your PHP to work with Excel. Of course, there are more objects that can be used to access a self-written OOP package. Classes are also as easy as accessing excel.
Use PHP COM to access Adobe Distiller
This last example is not an MS program. If your program has a PostScript file, you will be interested in this. Rewrite (distill) it Become a PDF document. Adobe has a
program called Distiller, which can generate an instance. The code is as follows:
$pdf = new COM("pdfdistiller.pdfdistiller.1");
?>
One thing to note is that The OLE identifier "pdfdistiller" given in the documentation for Distiller is invalid.
The most basic way to distill a file is:
$pdf->FileToPdf ($psfile, strOutputPDF '', strJobOptions "");
?>
This $psfile is the file name of this PostScript, strOutputPDF is the file name of the output file PDF. StrJobOptions is the parameter file name of Distiller. The last two parameters
are optional and default to the same name. This PS file name and PDF file name use this default Joboptions file. For example:
$pdf->FileToPdf ($psfile, "", "");
#Here $psfile can be Myfile.ps and will return the Myfile.pdf file.
?>
There are more methods and properties that can be used in Distiller. If you are interested, please refer to Adobe's technical documentation.
Aborts/Possible Issues
If something went wrong in your code, you might have created an instance but not closed it gracefully. Worst of all, the application may be held by this instance, and as a result, there will be multiple copies of the application in your application list, which will interfere with your application even if you correct the error. result. The solution is: after fixing a bug, clear them promptly
Before you start running again, use and end the task. For the same reason, at the end of your code, you should also close the program and delete the instance in time.
You have some tips for handling exceptions in com_get and com_set. For example:
$Version = Com_get($instance->Application,"Version");
will work in Word but will generate an error in Excel.
There are some objects that cannot be instantiated in PHP4. This is because this program requires a custom interface, which PHP4 does not support.
Why do we use it?
I hope these three examples can give you some clues to think about. PHP's COM allows you to access Windows 4 programs in PHP scripts. This code is simpler than ASP and can integrate other
PHP’s powerful database support functions. Microsoft is heavily marketing this COM technology in various aspects, under different names and structures, such as COM+ (Combine COM with
Microsoft Transaction Server MTS), ADO, OLE DB, OWC, Windows DNA, etc. The combination of PHP and Apache provides an open source solution.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The way to update ByBit exchanges varies by platform and device: Mobile: Check for updates and install in the app store. Desktop Client: Check for updates in the Help menu and install automatically. Web page: You need to manually access the official website for updates. Failure to update the exchange can lead to security vulnerabilities, functional limitations, compatibility issues and reduced transaction execution efficiency.

DeepSeek is a powerful intelligent search and analysis tool that provides two access methods: web version and official website. The web version is convenient and efficient, and can be used without installation; the official website provides comprehensive product information, download resources and support services. Whether individuals or corporate users, they can easily obtain and analyze massive data through DeepSeek to improve work efficiency, assist decision-making and promote innovation.

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

There are many ways to install DeepSeek, including: compile from source (for experienced developers) using precompiled packages (for Windows users) using Docker containers (for most convenient, no need to worry about compatibility) No matter which method you choose, Please read the official documents carefully and prepare them fully to avoid unnecessary trouble.

The official website entrance of the Coinsuper Exchange: https://www.coinsuper.com. The client download channels are: Windows client, macOS client, and mobile (iOS/Android). Registration requires an email, mobile phone number and password, and you need to complete real-name authentication before you can trade. The platform provides a variety of digital asset transactions, including Bitcoin, Ethereum, etc., with the transaction fee rate of 0.1% for both orders and acceptors. Security safeguards include cold wallet storage, dual-factor verification, anti-money laundering and anti-terrorism financing measures, and with security public

Gate.io is a popular cryptocurrency exchange that users can use by downloading its installation package and installing it on their devices. The steps to obtain the installation package are as follows: Visit the official website of Gate.io, click "Download", select the corresponding operating system (Windows, Mac or Linux), and download the installation package to your computer. It is recommended to temporarily disable antivirus software or firewall during installation to ensure smooth installation. After completion, the user needs to create a Gate.io account to start using it.

BITGet is a cryptocurrency exchange that provides a variety of trading services including spot trading, contract trading and derivatives. Founded in 2018, the exchange is headquartered in Singapore and is committed to providing users with a safe and reliable trading platform. BITGet offers a variety of trading pairs, including BTC/USDT, ETH/USDT and XRP/USDT. Additionally, the exchange has a reputation for security and liquidity and offers a variety of features such as premium order types, leveraged trading and 24/7 customer support.

Ouyi OKX, the world's leading digital asset exchange, has now launched an official installation package to provide a safe and convenient trading experience. The OKX installation package of Ouyi does not need to be accessed through a browser. It can directly install independent applications on the device, creating a stable and efficient trading platform for users. The installation process is simple and easy to understand. Users only need to download the latest version of the installation package and follow the prompts to complete the installation step by step.
