search
HomeBackend DevelopmentPHP TutorialPHP4(windows版本)中的COM函数_PHP

PHP4(windows版本)中的COM函数_PHP

Jun 01, 2016 pm 12:42 PM
comphpfunctionExampleobjectVersionprogram

 介绍

  内置于PHP4里的COM函数对于我们在win32环境下开发程序是相当有吸引力的,但是至今仍没有多少相关的技术文档。本文将以三个例子分别处理 MS office 2000 Word 、 Excel 、 Adobe Distiller 来说明如何在PHP中使用COM函数。

  COM技术是由Microsoft在几年前提出并开发的,本文中提到的相关名词有OLE, OLE Automation, ActiveX, COM ,这些词的意思都基本一样,都表示用一段封装的代码(对象)来完成一个windows 应用程序的一些功能。 PHP4 COM 函数可以连接一个对象实例,并使用它的方法与属性。

如果你想使用下面的例子源码,请参考一下我的配置。

Windows 98 - MS Office 2000
Apache 1.3.9 Windows
PHP4.02 Dev (08-20-00) Running as CGI


PHP4中的COM标记

现在让我们开始吧,用PHP4的COM来实例化一个组件,需要 new 操作符和对象的 "OLE 程序标识":

$instance = new COM("$identifier");

?>

因为COM是一个PHP4的保留字,它传送这个对象的标识给一个构造函数,现在得到了这个组件的一个实例,根据OOP类的性质,我们可以很容易地访问它的方法与属性。

例如:

$instance->[Object]->[method1]->[method2]->..->[property];

?>

就是这么简单!

OOP的结构在PHP下不能工作,(由于PHP语法的问题,属性的名字.值是非法字符,如点和圆括号等),所以PHP4提供了两个相应的函数:

bool com_set(class com_object, string property name, string property_value);

mixed com_get(class com_object, string property_name);

?>

最后,PHP4也支持DCOM技术,可以在远程计算机创建一个对象实例。

$Instance = new COM(string "Component name", string "remote_server_address");

?>

注意:这是用DCOM指令来设置PHP。在将来,PHP开发者提供Unix下对DCOM的支持。

 

标识、方法和属性

标识是一个如下的字串:

MS Word: "Word.Application" or "Word.Application.9"
MS Excel: "Excel.Application" or "Excel.Sheet"
ADOBE Acrobat: "Exch.application" or "PdfDistiller.PdfDistiller"

  对于最后一个标识,我要指明的是,获得正确的对象标识名不是一件容易的事。如果你不能访问VBA文档,你可以查找一下windows的注册表,在 HKEY_CLASSES_ROOT 中寻找一下,你就可以得到一些应用程序的名字。在你的机器上有效的对象标识放在 CLSID 子文件夹下。

  应用程序一般会提供文档说明它的COM方法和属性。在office2000中,你可以运行程序,打开VBA编辑器 ,选择对象编辑器。输入应用程序库中的一个方法名或属性名,然后,在下面的窗口中用鼠标右键选择一个类或成员名称,点帮助,你就会得到关于这个类或成员的描述。你也可以参考 MSDN。一个 Excel 的例子如下: http://msdn.microsoft.com/library/officedev/off2000/xltocobjectmodelapplication.htm


用COM函数操作 MS Word

现在,我们开始第一个例子吧:

#*********************************************************
# 本例来自Zend站点,略有改动
# 打开一个word实例,并新建一个文档Useless test.doc
# 输入一行文字 "This is a test2..."
#*********************************************************

#实例化一个对象

$word = new COM("word.application") or die("Unable to instantiate Word");

#取得并显示版本

print "Loaded Word, version {$word->Version}
";

#另一种方法去取得版本

$testversion = com_get($word->application,version);

print "Version using Com_get(): $testversion
";

#使其可见

$word->Visible = 1;

#创建新文件

$word->Documents->Add();

#写字符

$word->Selection->TypeText("This is a test...");

#保存

$word->Documents[1]->SaveAs("Useless test.doc");

#关闭

$word->Quit();

?>

你只要花几分钟来读这个程序,并参考Word的OLE 技术文档,你将学到几乎是你在自己程序中所需的全部的操作。


MS Excel在使用PHP的COM函数

  如同上面的Word的例子一样,你应学习这个例子的同时参考Excel的Visual Basic 编辑器中的对象浏览器的帮助文档。

#打开workbook和它的sheet,
#本例使用一个电子表格是Excel安装时自带的SOLVSAMP.XLS

$workbook = "C:Program FilesMicrosoft officeOfficeSamplesSOLVSAMP.XLS";
$sheet = "Quick Tour";

#实例化一个组件的对象
$ex = new COM("Excel.sheet") or Die ("Did not connect");

#取程序名称和版本
print "Application name:{$ex->Application->value}
" ;
print "Loaded version: {$ex->Application->version}
";

#打开工作本使我们可使用它
$wkb = $ex->application->Workbooks->Open($workbook) or Die ("Did not open");

#预保存原来的工作本,创建一个工作本的复本
$ex->Application->ActiveWorkbook->SaveAs("Ourtest");
#$ex->Application->Visible = 1; #本句去注释让Excel可见

# 读写一个单元格在一个新的工作表中
# 我们可以读到这个单元格 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

#最后,用新值重新计算这个单元格
$sheets->Calculate;
#必须的如果要计算,手动则是可选的
#可看到效果总价值(E13单元格)
$cell = $sheets->Cells(13,5) ; #Select the cell (Row Column number)
$number = Number_format($cell->value);
print "New Total cost =$$number - was ,732 before.
";
#根据计算公式,广告影响了公司的开销,这里将显示 ,809

#使用Excel内建的函数
# 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 ,000 loan @8% interest /10 months: $ $pay
";

#Should print monthly payment = $ -1,037.03

#可选,保存
$ex->Application->ActiveWorkbook->SaveAs("Ourtest");
#关闭,不提问
$ex->application->ActiveWorkbook->Close("False");
unset ($ex);

?>

  这个例子让你的PHP与Excel一同工作了,当然,也有更多的对象可以使用,访问一个自已写的OOP封装类也与访问excel一样容易。
用PHP的COM访问 Adobe Distiller

  这最后一个例子不是MS程序了,如果你的程序有一个PostScript文件,你会对这个有兴趣的,改写(蒸馏)它成为一个PDF文档. Adobe 有一个程序叫 Distiller ,它可以生成一个实例。代码如下:

$pdf = new COM("pdfdistiller.pdfdistiller.1");

?>

  有一点要注意的,是在Distiller 的文档中给出的这个OLE标识名 "pdfdistiller" 是无效的。

蒸馏一个文件的最基本的方法是:

$pdf->FileToPdf ($psfile, strOutputPDF '', strJobOptions "");

?>

这 $psfile 是这个PostScript的文件名, strOutputPDF 是输出文件PDF的文件名。 StrJobOptions 是Distiller的参数文件名,最后两个参数是可选的,默认是同一名字。 这PS文件名与PDF文件名,使用这个默认的Job options 文件。例如:

$pdf->FileToPdf ($psfile, "", "");
#这儿$psfile 可以是 Myfile.ps 将返回 Myfile.pdf 文件。

?>

在Distiller中有更多的方法和属性能被用。如果你感兴趣,请参考一下Adobe的技术文档。


中止/可能的问题

  如果你的代码中发生了什么错误,你可能会创建了一个实例,但没有正常地关闭它。最糟的是,这个应用程序可能被这个实例所保持,结果,在你的程序列表中就存在多份这个程序的副本,即使你更正了这个错误也会干扰你的结果。解决方法是:修正一个bug以来要及时清除它们在你重新开始运行之前,用 并结束任务。同样的原因,在你的代码最后,也要及时关闭这个程序并删除这个实例。

你有一些技巧在处理 com_get 和 com_set的异常时。例如:
$Version = Com_get($instance->Application,"Version");

将会在Word中工作但在Excel中会产生一个错误。

有一些对象在PHP4中是不能实例化的,这是因为这个程序要一个自定义的接口,但PHP4不支持。


为什么我们要用它?

  我希望这三个例子可以给你一些思考的线索,PHP的COM允许你在PHP的脚本中访问windows4的程序。这个代码比ASP简单并且能集成其它的PHP对数据库强大的支持功能。Microsoft 在各个方面都大力销售这个COM 技术,在不同的名称和结构下,如 COM+(Combine COM with Microsoft Transaction Server MTS), ADO, OLE DB, OWC, Windows DNA, 等等。 PHP 和 Apache的结合,提供了一个开放源码的解决方案。

 

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
What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?Apr 23, 2025 am 12:16 AM

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

How can you optimize PHP session performance?How can you optimize PHP session performance?Apr 23, 2025 am 12:13 AM

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

What is the session.gc_maxlifetime configuration setting?What is the session.gc_maxlifetime configuration setting?Apr 23, 2025 am 12:10 AM

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

How do you configure the session name in PHP?How do you configure the session name in PHP?Apr 23, 2025 am 12:08 AM

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment