|
|
 |
XII. COM and .Net (Windows)
COM is an acronym for Component Object Model; it is an object orientated
layer (and associated services) on top of DCE RPC (an open standard) and
defines a common calling convention that enables code written in any
language to call and interoperate with code written in any other language
(provided those languages are COM aware). Not only can the code be
written in any language, but it need not even be part of the same
executable; the code can be loaded from a DLL, be found in another
process running on the same machine, or, with DCOM (Distributed COM), be
found in another process on a remote machine, all without your code even
needing to know where a component resides.
There is a subset of COM known as OLE Automation which comprises a set of
COM interfaces that allow loose binding to COM objects, so that they can
be introspected and called at run-time without compile-time knowledge of
how the object works. The PHP COM extension utilizes the OLE
Automation interfaces to allow you to create and call compatible objects
from your scripts. Technically speaking, this should really be called
the "OLE Automation Extension for PHP", since not all COM objects are OLE
compatible.
Now, why would or should you use COM? COM is one of the main ways to glue
applications and components together on the Windows platform; using COM
you can launch Microsoft Word, fill in a document template and save the
result as a Word document and send it to a visitor of your web site. You
can also use COM to perform administrative tasks for your network and to
configure your IIS; these are just the most common uses; you can do much
more with COM.
Starting with PHP 5, this extension (and this documentation) was
rewritten from scratch and much of the old confusing and bogus cruft has
be removed. Additionally, we support the instantiation and creation of
.Net assemblies using the COM interoperability layer provided by
Microsoft.
Please read this article
for an overview of the changes in this extension in PHP 5.
COM functions are only available for the Windows version of PHP.
.Net support requires PHP 5 and the .Net runtime.
There is no installation needed to use these
functions; they are part of the PHP core. The windows version of PHP has built in
support for this extension. You do not need to load any additional
extension in order to use these functions.
You are responsible for installing support for the various COM objects
that you intend to use (such as MS Word); we don't and can't bundle all
of those with PHP.
Starting with PHP 5, you may use PHP's own the Section called foreach in Chapter 16 statement to iterate
over the contents of a standard COM/OLE IEnumVariant. In laymans terms,
this means that you can use foreach in places where you would have used
For Each in VB/ASP code.
Example 1. For Each in ASP <%
Set domainObject = GetObject("WinNT://Domain")
For Each obj in domainObject
Response.Write obj.Name & "<br />"
Next
%> |
|
Example 2. while() ... Next() in PHP 4 |
<?php
$domainObject = new COM("WinNT://Domain");
while ($obj = $domainObject->Next()) {
echo $obj->Name . "<br />";
}
?>
|
|
Example 3. foreach in PHP 5 |
<?php
$domainObject = new COM("WinNT://Domain");
foreach ($domainObject as $obj) {
echo $obj->Name . "<br />";
}
?>
|
|
Many COM objects expose their properties as arrays, or using array-style
access. In PHP 4, you may use PHP array syntax to read/write such a
property, but only a single dimension is allowed. If you want to read a
multi-dimensional property, you could instead make the property access
into a function call, with each parameter representing each dimension of
the array access, but there is no way to write to such a property.
PHP 5 introduces the following new features to make your life easier:
Access multi-dimensional arrays, or COM properties that require
multiple parameters using PHP array syntax. You can also write or set
properties using this technique.
Iterate SafeArrays ("true" arrays) using the the Section called foreach in Chapter 16 control structure. This works
because SafeArrays include information about their size. If an
array-style property implements IEnumVariant then you can also use
foreach for that property too; take a look at the Section called For Each for more information on this topic.
This extension will throw instances of the class com_exception
whenever there is a potentially fatal error reported by COM. All
COM exceptions have a well-defined code property that
corresponds to the HRESULT return value from the various COM operations.
You may use this code to make programmatic decisions on how to handle the
exception.
The behaviour of these functions is affected by settings in php.ini.
Table 1. Com configuration options | Name | Default | Changeable | Changelog |
|---|
| com.allow_dcom | "0" | PHP_INI_SYSTEM | Available since PHP 4.0.5. | | com.autoregister_typelib | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 4. Available since PHP 4.1.0. | | com.autoregister_verbose | "0" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 4. Available since PHP 4.1.0. | | com.autoregister_casesensitive | "1" | PHP_INI_ALL | PHP_INI_SYSTEM in PHP 4. Available since PHP 4.1.0. | | com.code_page | "" | PHP_INI_ALL | Available since PHP 5.0.0. | | com.typelib_file | "" | PHP_INI_SYSTEM | Available since PHP 4.0.5. |
For further details and definitions of the
PHP_INI_* constants, see the Appendix H.
Here's a short explanation of
the configuration directives.
- com.allow_dcom
When this is turned on, PHP will be allowed to operate as a D-COM
(Distributed COM) client and will allow the PHP script to instantiate
COM objects on a remote server.
- com.autoregister_typelib
When this is turned on, PHP will attempt to register constants from
the typelibrary of objects that it instantiates, if those objects
implement the interfaces required to obtain that information.
The case sensitivity of the constants it registers is controlled by the
com.autoregister_casesensitive
configuration directive.
- com.autoregister_verbose
When this is turned on, any problems with loading a typelibrary during
object instantiation will be reported using the PHP error mechanism.
The default is off, which does not emit any indication if there was
an error finding or loading the type library.
- com.autoregister_casesensitive
When this is turned on (the default), constants found in auto-loaded
type libraries will be registered case sensitively. See
com_load_typelib() for more details.
- com.code_page
It controls the default character set code-page to use when passing
strings to and from COM objects. If set to an empty string, PHP will
assume that you want CP_ACP, which is the default
system ANSI code page.
If the text in your scripts is encoded using a different
encoding/character set by default, setting this directive will save you
from having to pass the code page as a parameter to the COM class constructor. Please note that by
using this directive (as with any PHP configuration directive), your PHP
script becomes less portable; you should use the COM constructor parameter
whenever possible.
Note:
This configuration directive was introduced with PHP 5.
- com.typelib_file
When set, this should hold the path to a file that contains a list
of typelibraries that should be loaded on startup. Each line of
the file will be treated as the type library name and loaded as
though you had called com_load_typelib().
The constants will be registered persistently, so that the library
only needs to be loaded once. If a type library name ends with the
string #cis or #case_insensitive,
then the constants from that library will be registered case
insensitively.
The constants below are defined by this extension, and
will only be available when the extension has either
been compiled into PHP or dynamically loaded at runtime.
- Table of Contents
- COM -- COM class
- DOTNET -- DOTNET class
- VARIANT -- VARIANT class
- com_addref --
Increases the components reference counter [deprecated]
- com_create_guid --
Generate a globally unique identifier (GUID)
- com_event_sink --
Connect events from a COM object to a PHP object
- com_get_active_object --
Returns a handle to an already running instance of a COM object
- com_get --
Gets the value of a COM Component's property [deprecated]
- com_invoke --
Calls a COM component's method [deprecated]
- com_isenum -- Indicates if a COM object has an IEnumVariant interface for iteration [deprecated]
- com_load_typelib -- Loads a Typelib
- com_load --
Creates a new reference to a COM component [deprecated]
- com_message_pump --
Process COM messages, sleeping for up to timeoutms milliseconds
- com_print_typeinfo --
Print out a PHP class definition for a dispatchable interface
- com_propget -- Alias of com_get()
- com_propput -- Alias of com_set()
- com_propset -- Alias of com_set()
- com_release --
Decreases the components reference counter [deprecated]
- com_set --
Assigns a value to a COM component's property
- variant_abs --
Returns the absolute value of a variant
- variant_add --
"Adds" two variant values together and returns the result
- variant_and --
performs a bitwise AND operation between two variants and returns the result
- variant_cast --
Convert a variant into a new variant object of another type
- variant_cat --
concatenates two variant values together and returns the result
- variant_cmp --
Compares two variants
- variant_date_from_timestamp --
Returns a variant date representation of a unix timestamp
- variant_date_to_timestamp --
Converts a variant date/time value to unix timestamp
- variant_div --
Returns the result from dividing two variants
- variant_eqv --
Performs a bitwise equivalence on two variants
- variant_fix --
Returns the integer portion ? of a variant
- variant_get_type -- Returns the type of a variant object
- variant_idiv --
Converts variants to integers and then returns the result from dividing them
- variant_imp --
Performs a bitwise implication on two variants
- variant_int --
Returns the integer portion of a variant
- variant_mod --
Divides two variants and returns only the remainder
- variant_mul --
multiplies the values of the two variants and returns the result
- variant_neg --
Performs logical negation on a variant
- variant_not --
Performs bitwise not negation on a variant
- variant_or --
Performs a logical disjunction on two variants
- variant_pow --
Returns the result of performing the power function with two variants
- variant_round --
Rounds a variant to the specified number of decimal places
- variant_set_type --
Convert a variant into another type "in-place"
- variant_set --
Assigns a new value for a variant object
- variant_sub --
subtracts the value of the right variant from the left variant value and returns the result
- variant_xor --
Performs a logical exclusion on two variants
User Contributed Notes
COM and .Net (Windows)
mpg123 at thinstall dot com
09-May-2005 04:21
I found the lack of good online docs about how to access a windows environment very frustrating. I finally found something here: http://www.sitepoint.com/forums/showthread.php?t=92358 but it's a php4 way. I cleaned up the code, added introspection for methods and voila. Thanks and credit to the original posters.
<?php
function showServices($vComputerName, $vClass) {
$objLocator = new COM("WbemScripting.SWbemLocator");
if($vComputerName == "") $objService = $objLocator->ConnectServer();
else $objService = $objLocator->ConnectServer($vComputerName);
$objWEBM = $objService->Get($vClass);
$objProp = $objWEBM->Properties_;
$objMeth = $objWEBM->Methods_;
foreach($objMeth as $methItem) echo "Method: " . $methItem->Name ."\r\n";
echo "\r\n";
$objWEBMCol = $objWEBM->Instances_();
foreach($objWEBMCol as $objItem) {
echo "[" . $objItem->Name . "]\r\n";
foreach($objProp as $propItem) {
$tmp = $propItem->Name;
echo "$tmp: " . $objItem->$tmp . "\r\n";
}
echo "\r\n";
}
}
showServices("", "Win32_Processor");
showServices("", "Win32_LogicalDisk");
angelo [at] mandato <dot> com
25-Apr-2005 12:11
ADO + PHP5 + SQL DATE FIELDS
Using a COM("ADODB.Connection") object in PHP4 and PHP5 to return date fields in databases will have different results.
In PHP4, the date is returned as a string as represented in the database. In my case, '2005-04-11 11:35:44'.
In PHP5, the date is returned as a VARIANT type, when printed or implicitly casted would result as '4/11/2005 11:35:44 AM'.
For this example, the solution is to use the variant conversion function variant_date_to_timestamp() to convert the value to a Unix timestamp.
Please refer to this as an example. Other date types may be converted using one of the other variant_<convert> functions.
bruce at yourweb dot com dot au
23-Apr-2005 08:47
Simple convert xls to csv
<?php
$excel = new COM("excel.application") or die("Unable to instanciate excel");
print "Loaded excel, version {$excel->Version}\n";
$excel->DisplayAlerts = 0;
$excel->Workbooks->Open("C:\\mydir\\myfile.xls");
$excel->Workbooks[1]->SaveAs("c:\\mydir\\myfile.csv",6);
$excel->Quit();
$excel->Release();
$excel = null;
?>
mirtins at apollo dot lv
20-Apr-2005 05:10
hello
i have a problem with converting from XLS to XLM. I wont to use com(excel.aplication) and open xls and then saveas as xml, and i need parameters like word
$wdFormatDocument = 0;
$wdFormatTemplate = 1;
$wdFormatText = 2;
$wdFormatTextLineBreaks = 3;
$wdFormatDOSText = 4;
$wdFormatDOSTextLineBreaks = 5;
$wdFormatRTF = 6;
$wdFormatUnicodeText = 7;
$wdFormatHTML=8;
SaveAs("c:\\test_doc.html",8)
can someone send me for XLM
thanks!
Jack dot CHLiang at gmail dot com
11-Apr-2005 01:02
If you want to search an Excel file and don't connect with ODBC, you can try the function I provide. It will search a keyword in the Excel find and return its sheet name, text, field and the row which found the keyword.
<?php
$result = array();
searchEXL("C:/test.xls", "test", $result);
foreach($result as $sheet => $rs){
echo "Found at $sheet";
echo "<table width=\"100%\" border=\"1\"><tr>";
for($i = 0; $i < count($rs["FIELD"]); $i++)
echo "<th>" . $rs["FIELD"][$i] . "</th>";
echo "</tr>";
for($i = 0; $i < count($rs["TEXT"]); $i++) {
echo "<tr>";
for($j = 0; $j < count($rs["FIELD"]); $j++)
echo "<td>" . $rs["ROW"][$i][$j] . "</td>";
echo "</tr>";
}
echo "</table>";
}
function searchEXL($file, $keyword, &$result) {
$exlObj = new COM("Excel.Application") or Die ("Did not connect");
$exlObj->Workbooks->Open($file);
$exlBook = $exlObj->ActiveWorkBook;
$exlSheets = $exlBook->Sheets;
for($i = 1; $i <= $exlSheets->Count; $i++) {
$exlSheet = $exlBook->WorkSheets($i);
$sheetName = $exlSheet->Name;
if($exlRange = $exlSheet->Cells->Find($keyword)) {
$col = 1;
while($fields = $exlSheet->Cells(1, $col)) {
if($fields->Text == "")
break;
$result[$sheetName]["FIELD"][] = $fields->Text;
$col++;
}
$firstAddress = $exlRange->Address;
$finding = 1;
$result[$sheetName]["TEXT"][] = $exlRange->Text;
for($j = 1; $j <= count($result[$sheetName]["FIELD"]); $j++) {
$cell = $exlSheet->Cells($exlRange->Row ,$j);
$result[$sheetName]["ROW"][$finding - 1][$j - 1] = $cell->Text;
}
while($exlRange = $exlRange->Cells->Find($keyword)) {
if($exlRange->Address == $firstAddress)
break;
$finding++;
$result[$sheetName]["TEXT"][] = $exlRange->Text;
for($j = 1; $j <= count($result[$sheetName]["FIELD"]); $j++) {
$cell = $exlSheet->Cells($exlRange->Row ,$j);
$result[$sheetName]["ROW"][$finding - 1][$j - 1] = $cell->Text;
}
}
}
}
$exlBook->Close(false);
unset($exlSheets);
$exlObj->Workbooks->Close();
unset($exlBook);
$exlObj->Quit;
unset($exlObj);
}
?>
For more information, please visit my blog site (written in Chinese)
http://www.microsmile.idv.tw/blog/index.php?p=77
Gianluca GIMIGLIANO
13-Mar-2005 12:17
// NOTE: Using COM with windows XP with apache as a service
// - Compact a Microsoft Access Database
// Be careful $sourceFile and $destFile
//cannot be the same and
// $destFile must be unexistent
Function CompactMSAccess($sourceFile,$destFile) {
$com = new COM("JRO.JetEngine");
$com->CompactDatabase("Data Source=$sourceFile",
"Data Source=$destFile");
$com->Release();
$com=null;
return is_file($destFile);
//if $destFile exists it's a compact DB
}
CompactMSAccess('C:\directory\source.mdb',
'C:\directory\compact.mdb');
michael at example dot com
23-Feb-2005 03:42
After alot of trouble with IIS 6/Windows 2003 and PHP 5.0.2 I figured out how to use Imagemagick COM+/OLE interface. Seems you have to recreate the COM object after each convert() otherwise it will sometimes fail with very strange errors, since the PHP COM interface is not as stable as the old ASP one apparently is.
pelegk2 at walla DOT co DOT il
13-Feb-2005 11:49
Printing to a network printer :
read this note for :
// NOTE: Using COM with windows NT/2000/XP with apache as a service
// - Run dcomcnfg.exe
// - Find word application and click properties
// - Click the Security tab
// - Use Custom Access Permissions
// - Add the user who runs the web server service
// - Use Custom Launch permissions
// - Add the user who runs the web server service
THEN
// starting word
$word = new COM("word.application") or die("Unable to instanciate Word");
print "Loaded Word, version {$word->Version}\n";
// bring it to front
$word->Visible = 1;
//this is for example a printer on my network
$word->ActivePrinter = "\\\\192.168.4.201\\printer1";
// Open a word document, or anything else that word
// can read
$input ="c:\\test.html";
$word->Documents->Open($input);
$word->ActiveDocument->PrintOut();
// closing word
$word->Documents[1]->Close(false);
$word->Quit();
// free the object
$word->Release();
$word = null;
unset($word);
its based on :
at last i did it with lot's of thanks too :
http://il.php.net/manual/en/ref.com.php
cccso at mahidol dot ac dot th
11-Feb-2005 06:13
<?
$dbfile='D:\DB\log.mdb';
$conn = new COM("ADODB.Connection") or die("Cannot start ADO");
$conn->Open(DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=".$dbfile; );
$rs = $conn->Execute("Select * From tb_sql");
$tmp_result=$rs->Fields("count");
$result[$count]=$tmp_result->value;
echo "$count ==> $result[$count] <br>";
$rs->Close();
?>
if use version 4.3.10 with windows 2003 can not run "$conn->Open()"
06-Jan-2005 12:11
if you want to add a new hyperlink with excel :
$cell=$sheet->Range('O'.$j);
$cell->Hyperlinks->Add($cell ,'here_your_file');
I write this note because is very difficult to find
the good method to do that .
Merci beaucoup
sorin dot andrei at mymail dot ro
25-Sep-2004 05:24
[Editor's Note:
Serializing the object, storing it and then (on the next page) unserializing it WILL work.
End Note]
the big problem for PHP is it can't save in session an COM object
an samples code is here. This works just first time, then give the error:
Call to undefined method com::Refresh() on line $mMap->Refresh();
the reson is he can't save the object $mMap in session
<?php
session_start();
if (isset($_SESSION['map'])) {
$mMap = $_SESSION['map'];
}
else
{
$ArcIMSConnector = new COM ("aims.ArcIMSConnector") or die("can not create AIMS message object");
echo "Loaded ArcIMSConnector, <br>";
$ArcIMSConnector->ServerName = "map.sdsu.edu";
$ArcIMSConnector->ServerPort = 5300;
$mMap = new COM ("aims.Map") or die("can not create aims.Map message object");
echo "Loaded aims.Map, <br>";
print "AIMS-ServerName= $ArcIMSConnector->ServerName <br>";
$resultInit= $mMap->InitMap($ArcIMSConnector,"Worldgeography");
$mMap->Width = 400; $mMap->Height = 300; $mMap->BackColor = 15130848;
$_SESSION['map'] = $mMap;
}
$resultRefresh = $mMap->Refresh(); $urlImage = $mMap->GetImageAsUrl();
print "<br>urlImage=$urlImage<br>";
print "<br><IMG SRC='$urlImage'>";
?>
ferozzahid [at] usa [dot] com
24-Aug-2004 03:06
To pass a parameter by reference to a COM function, you need to pass VARIANT to it. Common data types like integers and strings will not work for it.
As an example, calling a function that retrieves the name of a person will look like:
$Name = new VARIANT;
$comobj = new COM("MyCOMOBj.Component") or die("Couldn't create the COM Component");
if(!$comobj->GetName($Name)) {
echo("Could not retrieve name");
}
else {
echo("The name retrieved is : " . $Name->value);
}
$Name->type will contain the type of the value stored in the VARIANT e.g. VT_BSTR.
Note For PHP 5:
Insted of '$Name->value', we can use only '$Name' for getting the value stored in the VARIANT. To get the type of the value stored in the VARIANT, use 'variant_get_type($Name)'.
Feroz Zahid
Shawn Coppock
11-Aug-2004 04:15
For those of us that are not experts with object models, if you have Microsoft Excel or Microsoft Word available, go into the Visual Basic Editor (Alt+F11). Now you can open the object browser window (F2) and see what you find.
If you select "Word" in the object browser, then the classes and members of that class are displayed below. For example, if you click on "Selection" in the classes column, and then "Font" in the members column, you will then see "Property Font As Font Member of Word.Selection" displayed at the bottom. Click on the "Font" link there.
Click on Word "Selection" again in the classes column, and then "PageSetup" in the members column, you will then see "Property PageSetup As PageSetup Member of word.Selection" displayed at the bottom. Click on the "PageSetup" link there.
Using the above examples, you can now formulate your Word Document from php. Here is a simple example that creates a 1 & 1/2" space for text based on the margin settings & with dark red text and an 8pt Helvetica font face:
$content = "Insert Sample Text Here\n\nThis starts a new paragraph line.";
$word= new COM("word.application") or die("Unable to create Word document");
print "Loaded Word, version {$word->Version}\n";
$word->Visible = 0;
$word->Documents->Add();
$word->Selection->PageSetup->LeftMargin = '3"';
$word->Selection->PageSetup->RightMargin = '4"';
$word->Selection->Font->Name = 'Helvetica';
$word->Selection->Font->Size = 8;
$word->Selection->Font->ColorIndex= 13; //wdDarkRed = 13
$word->Selection->TypeText("$content");
$word->Documents[1]->SaveAs("some_tst.doc");
$word->quit();
echo "done";
This example (and others) worked for me with Microsoft Word 10.0 Object Library (MS Word 2002), Apache & PHP on Windows XP. Experimenting using the Visual Basic editor will yield some amazing documents from PHP as it will help you see the relationships of the objects used and give you an idea as to how to construct your code. But be prepared for an occaisional PHP.exe crash if your code is way off base.
Hope this helps!
Jason Neal
21-Jul-2004 03:48
If you are having issues with the outlook.application locking up when you try to access it, ensure that your apache server is running in the context of a user on the machine instead of the system account.
appleapril04pear at cherrypixelbananapiz dot de
13-Jul-2004 08:36
If you want to use ms indexing server by querying it from ms sql server in a stored procedure with parameters you can do the following:
1.) Create the Catalog named 'myIndexServer' in indexing server
2.) execute addLinkedServer in query analyzer
EXEC sp_addlinkedserver
@server = 'myIndexServer',
@srvproduct = 'Index Server',
@provider = 'MSIDXS',
@datasrc = 'myIndexServer'
GO
in case myIndexServer already exist choose another name or
delete it (be carefull)
EXEC sp_dropserver myIndexServer
GO
3.) Write the following string in query analyzer
declare @sql varchar(1000)
declare @searchFor varchar(400)
set @searchFor = 'phporsomething'
set @sql =' SELECT Path, Filename
FROM OPENQUERY( pmsIndexServer,
''SELECT Path, Filename FROM
pmsProtokollAnhaengeIndex..SCOPE()
WHERE CONTAINS( '''''+@searchFor+''''' )'' ) AS dres' -- end of long sql-string
exec (@sql)
Attention 5 times ' !!!
4.) Execute the string (F5)
5.) Create a simple stored procedure and copy the string from step 3. Make @searchFor an parameter of your sp
6.) You are done, lean back, enjoy and relax
To contact me remove the fruits.
martijn at lico dot nl
20-Jun-2004 08:30
A nice feature you get with COM is the ability to connect to the Windows Management Instrumentation (WMI for short). This allows you to monitor various system statistics (e.g. disk space en cpu usage) of local and remote systems.
Small example:
<?php
$hostname = ".";
$wmi = new COM("WinMgmts:{impersonationLevel=impersonate}
//{$hostname}/root/cimv2");
$cpus = $wmi->ExecQuery("Select * from Win32_Processor");
foreach ($cpus as $cpu)
{
echo trim($cpu->Name)." {$cpu->MaxClockSpeed}MHz {$cpu->LoadPercentage}%\n";
}
?>
will give you this:
Intel Pentium III processor 860MHz 1%
Intel Pentium III processor 860MHz 2%
For more examples, see this post on my weblog: http://wiljedatikinjemond.com/article.php/2004061815294318
angelo [at] mandato <dot> com
03-Jun-2004 02:37
Useful PHP MSWord class I created to do some simple file conversions. This class could have a lot more to it but I am not familiar with all the COM MS Word function calls.
<?php
$wdFormatDocument = 0;
$wdFormatTemplate = 1;
$wdFormatText = 2;
$wdFormatTextLineBreaks = 3;
$wdFormatDOSText = 4;
$wdFormatDOSTextLineBreaks = 5;
$wdFormatRTF = 6;
$wdFormatUnicodeText = 7;
$wdFormatHTML=8;
class MSWord
{
var $handle;
function MSWord($Visible = false)
{
$this->handle = new COM("word.application") or die("Unable to instanciate Word");
$this->handle->Visible = $Visible;
}
function Open($File)
{
$this->handle->Documents->Open($File);
}
function NewDocument()
{
$this->handle->Documents->Add();
}
function WriteText( $Text )
{
$this->handle->Selection->Typetext( $Text );
}
function DocumentCount()
{
return $this->handle->Documents->Count;
}
function SaveAs($File, $Format = 0 )
{
$this->handle->ActiveDocument->SaveAs($File, $Format);
}
function Save()
{
$this->handle->ActiveDocument->Save();
}
function Close()
{
$this->handle->ActiveDocument->Close();
}
function GetVersion()
{
return $this->handle->Version;
}
function GetHandle()
{
return $this->handle;
}
function Quit()
{
if( $this->handle )
{
$this->handle->Quit();
$this->handle->Release();
$this->handle = null;
}
}
};
?>
Example 1, opens an html file, writes text to it, then saves it as a document:
<?php
$input = "C:\\test.htm";
$output = "C:\\test.doc";
$Word = new MSWord;
$Word->Open($input);
$Word->WriteText("This is a test ");
$Word->SaveAs($output);
$Word->Quit();
?>
Example 2, opens an html file, then saves it as a rtf file:
<?php
$input = "C:\\test.htm";
$output = "C:\\test.rtf";
$Word = new MSWord;
$Word->Open($input);
$Word->SaveAs($output, $wdFormatRTF);
$Word->Quit();
?>
angelo [at] mandato <dot> com
18-May-2004 07:30
Useful PHP functions I created (similar to other standard PHP database functions) for working with an ADO datasource:
<?php
$ADO_NUM = 1;
$ADO_ASSOC = 2;
$ADO_BOTH = 3;
function ado_connect( $dsn )
{
$link = new COM("ADODB.Connection");
$link->Open($dsn);
return $link;
}
function ado_close( $link )
{
$link->Close();
}
function ado_num_fields( $rs )
{
return $rs->Fields->Count;
}
function ado_error($link)
{
return $link->Errors[$link->Errors->Count-1]->Number;
}
function ado_errormsg($link)
{
return $link->Errors[$link->Errors->Count-1]->Description;
}
function ado_fetch_array( $rs, $result_type, $row_number = -1 )
{
global $ADO_NUM, $ADO_ASSOC, $ADO_BOTH;
if( $row_number > -1 ) $rs->Move( $row_number, 1 );
if( $rs->EOF )
return false;
$ToReturn = array();
for( $x = 0; $x < ado_num_fields($rs); $x++ )
{
if( $result_type == $ADO_NUM || $result_type == $ADO_BOTH )
$ToReturn[ $x ] = $rs->Fields[$x]->Value;
if( $result_type == $ADO_ASSOC || $result_type == $ADO_BOTH )
$ToReturn[ $rs->Fields[$x]->Name ] = $rs->Fields[$x]->Value;
}
$rs->MoveNext();
return $ToReturn;
}
function ado_num_rows( $rs )
{
return $rs->RecordCount;
}
function ado_free_result( $rs )
{
$rs->Close();
}
function ado_query( $link, $query )
{
return $link->Execute($query);
}
function ado_fetch_assoc( $rs, $row_number = -1 )
{
global $ADO_ASSOC;
return ado_fetch_array( $rs, $ADO_ASSOC, $row_number);
}
function ado_fetch_row( $rs, $row_number = -1 )
{
global $ADO_NUM;
return ado_fetch_array( $rs, $ADO_NUM, $row_number);
}
function ado_field_len( $rs, $field_number )
{
return $rs->Fields[$field_number]->Precision;
}
function ado_field_name( $rs, $field_number )
{
return $rs->Fields[$field_number]->Name;
}
function ado_field_scale( $rs, $field_number )
{
return $rs->Fields[$field_number]->NumericScale;
}
function ado_field_type( $rs, $field_number )
{
return $rs->Fields[$field_number]->Type;
}
?>
The aod version was a typo.
markshane1 at fuse dot net
10-May-2004 07:41
Here is a COM function that creates an excel spreadsheet with any number of worksheets, containing data from a matching number of SQL queries. Be ware of the upper limit of excel worksheets. This function properly shuts down Excel on the server.
/***************************/
function WriteExcel($strPath,$astrSheetName,$astrSQL){
/* This function takes a file save path, and array of sheet names and a corresponding array */
/* of SQL queries for each sheet and created a multi-worksheet excel spreadsheet*/
$C_NAME=__CLASS__."::".__FUNCTION__;
$dbs=new clsDB;
$exapp = new COM("Excel.Application") or Die ("Did not connect");
$intSheetCount=count($astrSheetName);
$wkb=$exapp->Workbooks->Add();
$exapp->Application->Visible = 1;
for ($int=0;$int<$intSheetCount;$int++){
$sheet=$wkb->Worksheets($int+1);
$sheet->activate;
$sheet->Name=$astrSheetName[$int];
$intRow=1;
$qrySQL=$dbs->GetQry($astrSQL[$int],$C_NAME,__LINE__);
$rstSQL=$qrySQL->fetchRow(DB_FETCHMODE_ASSOC);
$astrKeyNames=array_keys($rstSQL);
$intCols=count($astrKeyNames);
$qrySQL=$dbs->GetQry($astrSQL[$int],$C_NAME,__LINE__);
while($rstSQL=$qrySQL->fetchRow(DB_FETCHMODE_ASSOC)){
$strOut="";//initialize the output string
for ($int2=0;$int2<$intCols;$int2++){//we start at 1 because don't want to output the table's index
if($intRow==1){
$strOut=$astrKeyNames[$int2];
}else{
$strOut=$rstSQL[$astrKeyNames[$int2]];
}
$sheet->activate;
$cell=$sheet->Cells($intRow,($int2+1));//->activate;
$cell->Activate;
$cell->value = $strOut;
}//end of colcount for loop
$intRow++;
}//end while loop
}//end sheetcount for loop
if (file_exists($strPath)) {unlink($strPath);}
$wkb->SaveAs($strPath);
$wkb->Close(false);
unset($sheet);
$exapp->Workbooks->Close(false);
unset($wkb);
$exapp->Quit;
unset($exapp);
unset($dbs);
}//function WriteExcel
Haseldow
05-Apr-2004 08:31
Simple example for creating your own dll's which can be called as COM objects in PHP:
First create your ActiveX dll (Visual Basic):
Name your project as "foo" and class as "bar".
'---start VB code---
Public Function hello() As String
hello = "Hello World!"
End Function
'---end VB code---
Then make the dll and register it with regsvr32.exe
Now create your PHP script:
<?php
$obj = new COM("foo.bar");
$output=$obj->hello(); echo $output; ?>
mark dickens at mindspring dot com
29-Feb-2004 11:03
Just a note to those wanting to use COM to interface to printers under Windows 2000/XP. If it doesn't work or seems to hang, try changing the logon identity under which the Apache (assuming you're using Apache) service is running from the System account to another account. By default most services will install to run under the System account and although the System account has total authority on the computer it is running on, it has no authority outside of that realm as I understand it. Apparently accessing printers is considered "outside the realm". I used this technique to interface a Dymo thermal label printer to my server and it works now.
Awadhaj at hotmail dot com
28-Feb-2004 08:44
Hi php Society!
Using COM function u can run your own simple dlls !
#if u are an ADMINISTRATOR#
first: use the windows regsver32.exe to register ur dll.
second:
<php?
$myDLL=new COM("myDll");
// then u can invoke eny method
$myDLL->DoSomething;
// or get any proerty
$xVar=$myDLL->GetSomeValue
?>
platiumstar at canada dot com
12-Feb-2004 06:08
I didn't found any working examples of PHP using the MSMQ COM object, so I made up one, thought I share it with everybody..it works ok.
You have to create a local Public message queue named "TestQueue" first.
define(MQ_SEND_ACCESS , 2);
define(MQ_DENY_NONE , 0);
$msgQueueInfo = new COM("MSMQ.MSMQQueueInfo") or die("can not create MSMQ Info object");
$msgQueueInfo->PathName = ".\TestQueue";
$msgQueue = new COM("MSMQ.MSMQQueue") or die("can not create MSMQ object");
$msgQueue=$msgQueueInfo->Open(MQ_SEND_ACCESS, MQ_DENY_NONE );
$msgOut = new COM("MSMQ.MSMQMessage") or die("can not create MSMQ message object");
$msgOut->Body = "Hello world!";
$msgOut->Send($msgQueue);
$msgQueue->Close();
unset($msgOut);
unset($msgQueue);
unset($msgQueueInfo);
enjoy
PS
kleontiv -at- combellga -dot- ru
15-Dec-2003 02:47
And here is an example of using ADSI via ADODB. This sample is unique because only ADODB can provide recursive Active directory searching and listing. But ADODB can only READ Active directory. So you can find something by ADODB and then modify that directly by ADSI.
With previos example this help build you PHP coded interface to Menaging and browsing Microsoft Active Directory.
Also ADODB on ADSI helps you sort recordset and search on it.
<?php
$objConnection = new COM ("ADODB.Connection") ;
$objConnection->Open("Provider=ADsDSOObject;user id=DOMAIN\\login;password=your_passowrd;") ;
$objCommand = new COM("ADODB.Command") ;
$objCommand->ActiveConnection = $objConnection ;
$Cmd = "<LDAP://dc=mydomain,dc=com>;" ;
$Cmd .= "(&(objectClass=user)(mail=*)(!cn=SystemMailbox*));" ;
$Cmd .= "name,mail,telephoneNumber;subtree" ;
$objCommand->Properties['Sort On']->Value = "name" ;
$objCommand->CommandText = $Cmd ;
$objRecordSet = $objCommand->Execute() ;
$OrderNumber = 0 ;
while(!$objRecordSet->EOF())
{
$OrderNumber ++ ;
$nn = $objRecordSet->Fields['name']->Value ;
$mm = $objRecordSet->Fields['mail']->Value ;
$ph = $objRecordSet->Fields['telephoneNumber']->Value ;
echo "$OrderNumber: $nn mail: $mm phone: $ph<br>" ;
$objRecordSet->MoveNext() ;
}
Echo "===========================<br>" ;
Echo "All MailBoxes: " ;
Echo $objRecordSet->RecordCount() ;
$objRecordSet->Close() ;
$objCommand->Close() ;
$objConnection->Close() ;
unset($objRecordSet) ;
unset($objCommand) ;
unset($objConnection) ;
?>
kleontiv -at- combellga -dot- ru
15-Dec-2003 12:27
I think some one wants to access to Microsoft Active Directory using ADSI with different credential by PHP. You can also do it via pure LDAP but using ADSI it is more simpler.
On VB, VBS or ASP you can do like folowing (so not trivial):
<%
Set dso = GetObject("LDAP:")
Set DsObj = dso.OpenDSObject( _
"LDAP://DC=mydomain,DC=com", _
"DOMAIN\login", _
"password", _
ADS_SECURE_AUTHENTICATION + ADS_SERVER_BIND + ADS_USE_ENCRYPTION)
for each Obj in DsObj
Response.Write Obj.name & " with class of: " & Obj.class & "<br>"
next
%>
On PHP you can do like that:
<?php
$ADSI = new COM("LDAP:") ;
$DsObj
| |