PHP
downloads | documentation | faq | getting help | mailing lists | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

COM> <cpdf_translate
Last updated: Sun, 25 Nov 2007

view this page in

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.

安裝

本擴充功能作為 PHP 核心的一部分,無需安裝即可使用。

PHP 的 Windows 版本已經內置該擴充功能的支援。無需載入任何附加擴充功能即可使用這些函式。

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.

For Each

Starting with PHP 5, you may use PHP's own foreach 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 />"

?>

Arrays and Array-style COM properties

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 foreach 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 COM for more information on this topic.

Exceptions (PHP 5)

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.

執行時期設定

這些函式的行為受 php.ini 的影響。

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.
有關 PHP_INI_* 常數進一步的細節與定義參見php.ini 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 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.

資源類型

This extension defines a reference to a COM component returned by deprecated com_load() (this function does not exist in PHP 5; use the COM class instead).

預設常數

以下常數由擴充功能定義,因此只有在擴充功能被編譯到 PHP 中,或者在執行時被動態載入後才有效。

CLSCTX_INPROC_SERVER (integer)
CLSCTX_INPROC_HANDLER (integer)
CLSCTX_LOCAL_SERVER (integer)
CLSCTX_REMOTE_SERVER (integer)
CLSCTX_SERVER (integer)
CLSCTX_ALL (integer)
VT_NULL (integer)
VT_EMPTY (integer)
VT_UI1 (integer)
VT_I2 (integer)
VT_I4 (integer)
VT_R4 (integer)
VT_R8 (integer)
VT_BOOL (integer)
VT_ERROR (integer)
VT_CY (integer)
VT_DATE (integer)
VT_BSTR (integer)
VT_DECIMAL (integer)
VT_UNKNOWN (integer)
VT_DISPATCH (integer)
VT_VARIANT (integer)
VT_I1 (integer)
VT_UI2 (integer)
VT_UI4 (integer)
VT_INT (integer)
VT_UINT (integer)
VT_ARRAY (integer)
VT_BYREF (integer)
CP_ACP (integer)
CP_MACCP (integer)
CP_OEMCP (integer)
CP_UTF7 (integer)
CP_UTF8 (integer)
CP_SYMBOL (integer)
CP_THREAD_ACP (integer)
VARCMP_LT (integer)
VARCMP_EQ (integer)
VARCMP_GT (integer)
VARCMP_NULL (integer)
NORM_IGNORECASE (integer)
NORM_IGNORENONSPACE (integer)
NORM_IGNORESYMBOLS (integer)
NORM_IGNOREWIDTH (integer)
NORM_IGNOREKANATYPE (integer)
NORM_IGNOREKASHIDA (integer)
DISP_E_DIVBYZERO (integer)
DISP_E_OVERFLOW (integer)
MK_E_UNAVAILABLE (integer)

參見

For further information on COM read the » COM specification or perhaps take a look at Don Box's » Yet Another COM Library (YACL). You might find some additional useful information in our FAQ for PHP and COM. If you're thinking of using MS Office applications on the server side, you should read the information here: » Considerations for Server-Side Automation of Office.

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 — 別名 com_get
  • com_propput — 別名 com_set
  • com_propset — 別名 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


COM> <cpdf_translate
Last updated: Sun, 25 Nov 2007
 
add a note add a note User Contributed Notes
COM
larrywalker at at chelseagroton dot com
02-Sep-2008 08:53
To run a php script in a background process and pass it you var use

<?php

$WshShell
= new COM("WScript.Shell");
$oExec = $WshShell->Run("c:\\xampp\\php\\php.exe

c:\\xampp\\Not_on_Web\\ftptestback.php --user=$username"
, 7, false);

?>

Works for me.
monica at digitaldesignservices dot com
27-Dec-2007 02:41
Working with Word 2003 COM object. 

Have you been trying to work with the Word.Application COM and the Word Document would crash and the PHP script would hang? 

Turns out that there is an issue within the Office COM object that doesn't let the web application (IIS, Apache) scripting engine release the object after instancing the COM.  The Service Pack 3 office update claims to remedy this.  Will test and post findings.
Bandorka
12-Dec-2007 08:52
Guys, I found a way to pass parameters from PHP to Crystal Reports 11 without hanging!!!!

So the problem is the prompt for params dialog:

$ObjectFactory= New COM("CrystalReports11.ObjectFactory.1");
  $crapp = $ObjectFactory->CreateObject("CrystalDesignRunTime.Application");
  $creport = $crapp->OpenReport($my_report, 1);
 
 
     
$creport->Database->Tables->
Item(1)->ConnectionProperties['User ID'] =  'blablabla';

$creport->Database->Tables->
Item(1)->ConnectionProperties['Password'] = 'blablabla';

$creport->FormulaSyntax = 0;
$creport->RecordSelectionFormula= "{TABLENAME.FIELDNAME}='$USRID'";

//This is it, this avoids the hanging!
$creport->EnableParameterPrompting = 0;

$creport->DiscardSavedData;
$creport->ReadRecords();

//it is essential to assign the param values here after the readrecords otherwise you will not pass anything...

$zz= $creport->ParameterFields(1)->SetCurrentValue(500);
 
 $creport->ExportOptions->DiskFileName=$exp_pdf;
  $creport->ExportOptions->PDFExportAllPages=true;
  $creport->ExportOptions->DestinationType=1;   $creport->ExportOptions->FormatType=31;
  $creport->Export(false);

$creport->ExportOptions->DiskFileName=$exp_xls;
  $creport->ExportOptions->PDFExportAllPages=true;
  $creport->ExportOptions->DestinationType=1;   $creport->ExportOptions->FormatType=29;
  $creport->Export(false);

$len = filesize($exp_pdf);
header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=reportin.pdf");
readfile("reportin.pdf");

//------ Release the variables
$creport = null;
$crapp = null;
$ObjectFactory = null;

Have fun,
Andras
neoray1 at caramail dot com
27-Nov-2007 07:08
On exemple for use indexer there are an error, this correct code

$searchstring="news";
         $INDEXCATALOG="YourCatalogName";
         $objIndexServer = new COM("ADODB.Connection") or die("Cannot start ADO");
        $objIndexServer->Provider = "msidxs";
        $objIndexServer->Open($INDEXCATALOG);
      
        $sql="SELECT DocTitle, VPath, Path, Filename, Access, HitCount, Rank "
            ."FROM SCOPE('DEEP TRAVERSAL OF \"d:\inetpub\intranet \"') "
            ."WHERE ((CONTAINS(' \"$searchstring\" ') >0) "
            ."AND ((Path NOT LIKE '%\_vti%') AND (Path NOT LIKE '%\_private%') "
            ."AND (Filename NOT LIKE 'search.php'))) ORDER BY Rank DESC";
      
        $objRS = $objIndexServer->Execute("$sql"); # submit the query
      
       // while (!$rs->EOF)  $rs not exist the really result is $objRS
        while (!$objRS->EOF) //create output
        {
            echo
            $objRS->Fields["DOCTITLE"]->value." -- "
            .$objRS->Fields["FILENAME"]->value." -- "
            .date("d.M.y",$objRS->Fields["ACCESS"]->value)." -- "
            .$objRS->Fields["HITCOUNT"]->value." -- "
            .($objRS->Fields["RANK"]->value/10)."% ----> "
            .$objRS->Fields["VPATH"]->value
            ."<br>";
            $objRS->MoveNext();
        }

Thanks you at dirk_hahn for the good code
tomfmason at nospam-gmail dot com
08-Oct-2007 07:26
To get the cpu load percentage you can do something like this.

<?php
$wmi
= new COM('winmgmts://');
$processor = $wmi->ExecQuery("SELECT * FROM Win32_Processor");
foreach(
$processor as $obj){
   
$cpu_load_time = $obj->LoadPercentage;
}
echo
$cpu_load_time;
?>

reference http://msdn2.microsoft.com/en-us/library/aa394373.aspx

To list current apache instances

<?php
$wmi
= new COM('winmgmts://');
$processes = $wmi->ExecQuery("SELECT * FROM Win32_Process WHERE Name = 'httpd.exe'");
foreach(
$processes as $process){
    echo
$process->CommandLine . "<br />";
    echo
$process->ProcessId . "<br />";
}
?>

reference http://msdn2.microsoft.com/en-us/library/aa394372.aspx

To run a php script in a background process

<?php
$dir
= "C:\\path\\to\\dir";
$php_path = "C:\\path\\to\\php.exe";
$file = "somescript.php";
//send time current timestamp
$cmd_options = "-t " . time();
$wscript = new COM('WScript.Shell');
$wscript->Run("cmd /K CD $php_path $dir\\$file  &  ", 0, false);
?>

Enjoy

Tom
sk89q
27-Sep-2007 11:13
The only way I've been able to call Win32 API functions with PHP5 has been through COM and DynamicWrapper.

Get DynamicWrapper at:
http://ourworld.compuserve.com/homepages/Guenter_Born/
WSHBazaar/WSHDynaCall.htm
(remove new line)

Here's an example to play a beep sound with your computer speaker:
<?php
$com
= new COM("DynamicWrapper");
$com->Register("KERNEL32.DLL", "Beep", "i=ll", "f=s", "r=l");
$com->Beep(5000, 100);
?>
naveed at php dot net
10-Mar-2007 05:24
Here is a spell check implementation that displays the suggestion list for each misspelled word.

<?php
function SpellCheck($input)
{
   
$word=new COM("word.application") or die("Cannot create Word object");
   
$word->Visible=false;
   
$word->WindowState=2;
   
$word->DisplayAlerts=false;
   
$doc=$word->Documents->Add();
   
$doc->Content=$input;
   
$doc->CheckSpelling();
   
$result= $doc->SpellingErrors->Count;
    if(
$result!=0)
    {
        echo
"Input text contains misspelled words.\n\n";
        for(
$i=1; $i <= $result; $i++)
        {       
            echo
"Original Word: " .$doc->SpellingErrors[$i]->Text."\n";
           
$list=$doc->SpellingErrors[$i]->GetSpellingSuggestions();
            echo
"Suggestions: ";
            for(
$j=1; $j <= $list->Count; $j++)
            {
               
$correct=$list->Item($j);
                echo
$correct->Name.",";
            }
            echo
"\n\n";
        }
    }
    else
    {
        echo
"No spelling mistakes found.";
    }
   
$word->ActiveDocument->Close(false);
   
$word->Quit();
   
$word->Release();
   
$word=null;
}

$str="Hellu world. There is a spellling error in this sentence.";
SpellCheck($str);
?>
Francois-R dot Boyer at PolyMtl dot ca
13-Feb-2007 08:32
As allan666 pointed out, your Office application may not terminate correctly, and leave processes in the background, if a dialog box was opened by the application.

I had the problem when trying to call Access VBA scripts from PHP; the call was working but Access would never quit.  The problem was that the Apache server is running as SYSTEM, and not a user we normally use to run Office.  And as the first time a user runs Office, it asked the SYSTEM user to enter its name and initials! ;-)

To correct this problem: Stop Apache, go to Services, Apache, Properties, "Log On" tab, and check "Allow service to interact with desktop.  Restart Apache, then open your office application, in a page loaded by the Apache server, with a small PHP code like this, :
<?php
$app
= new COM("Access.Application"); // or Word.Application or Excel.Application ...
$app->Visible = true; // so that we see the window on screen
?>

Put the name you want and quit the application.  Now your Office application should terminate correctly the next time you load it with a COM object in PHP.  You can stop Apache uncheck the "Allow service to interact with desktop", and restart Apache if you like.  I don't even require a Quit or anything to be sent to Access, it quits automatically when PHP terminates.

And for those who wish to know how I'm calling Access VBA scripts, instead of using ODBC or any other way to send SQL requests, which does not seem to work to call VBA scripts, I open the database as a COM object and it works fine:
<?php
$db_com
= new COM("pathname of the file.mdb");
$result = $db_com->Application->Run("function_name", param1, param2 …);
?>
wiliamfeijo at gmail dot com
05-Feb-2007 12:10
This code use a Crystal Reports file with a connection on
 Oracle 9i Database, suports manipulate and refresh data
 and export to PDF file:

------ REMEMBER ------
These functions are only available if you had instaled the
Crystal Reports Developer Edition. Catch the trial on the
http://www.businessobjects.com web site.

//------  Variables ------
$my_report = "C:\\rel_apontamento.rpt";
$my_pdf = "C:\\teste.pdf";

//------ Create a new COM Object of Crytal Reports XI ------
$ObjectFactory= new
 COM("CrystalReports11.ObjectFactory.1");

//------ Create a instance of library Application -------
$crapp
=$ObjectFactory->
CreateObject("CrystalDesignRunTime.Application.11");

//------ Open your rpt file ------
$creport = $crapp->OpenReport($my_report, 1);

//------ Connect to Oracle 9i DataBase ------
$crapp->LogOnServer('crdb_oracle.dll','YOUR_TNS',
'YOUR_TABLE','YOUR_LOGIN','YOUR_PASSWORD');

//------ Put the values that you want --------
$creport->RecordSelectionFormula=
"{YOUR_TABLE.FIELD}='ANY_VALUE'";

//------ This is very important. DiscardSavedData make a
 Refresh in your data -------
$creport->DiscardSavedData;

//------ Read the records :-P -------
$creport->ReadRecords();

//------ Export to PDF -------
$creport->ExportOptions->DiskFileName=$my_pdf;
$creport->ExportOptions->FormatType=31;
$creport->ExportOptions->DestinationType=1;
$creport->Export(false);

//------ Release the variables
$creport = null;
$crapp = null;
$ObjectFactory = null;

It's functional and perfectly !!!!!!!

Thanks.....
03-Oct-2006 04:11
If someone want to get a COM object out of a DCOM object can do something like that:

<?php
  $dcom_obj
= new COM('dacom.object','remotehost') or die("Unable to get DCOM object!");
 
$com_obj = new Variant(NULL);
 
$dcom_obj->Get_Module($com_obj); //user function which returns a custom IDispatch (casted as variant*)
?>

Hopefully this will help someone, because it took me quite long to figure this out.
kiotech at hotmail dot com
18-Jul-2006 06:35
For use parameters with PHP this is a Code Example
$ObjectFactory= New COM("CrystalReports11.ObjectFactory.1");
  $crapp = $ObjectFactory->CreateObject("CrystalDesignRunTime.Application");
  $creport = $crapp->OpenReport("//report1.rpt", 1);

  
      $z= $creport->ParameterFields(1)->SetCurrentValue("Mango");
      $z= $creport->ParameterFields(2)->SetCurrentValue(5000);

  $creport->ExportOptions->DiskFileName="reportin.pdf";
  $creport->ExportOptions->PDFExportAllPages=true;
  $creport->ExportOptions->DestinationType=1;   $creport->ExportOptions->FormatType=31;
  $creport->Export(false);

$len = filesize("reportin.pdf");
header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=reportin.pdf");
readfile("reportin.pdf");
djogopatrao at gmail dot com
22-Mar-2006 10:44
Since my last post, I struggled hard to find a way to pass parameters to Crystal. Luckly, all I needed was to restrict results from a query, so I found this simple solution:

  // by dfcp/mar/06
  $ObjectFactory= New COM("CrystalReports11.ObjectFactory.1");
  $crapp = $ObjectFactory->CreateObject("CrystalDesignRunTime.Application");
  $creport = $crapp->OpenReport($my_report, 1);

  $creport->FormulaSyntax = 0;
  $creport->RecordSelectionFormula = "{cadastro.id}>10 and {cadastro.id}<20";

notice that RecordSelectionFormula must be in Crystal Syntax, and the FormulaSyntax=0 makes it work 100% of the time (I suspect that it's bug, although they1 don't seem to think so).

If you need to pass parameters to, say, multiply some field by, IMHO the right way is to use ParameterFields, but the code above hangs on the last line:

$z = $creport->ParameterFieldDefinitions->Item(1); //gets the first parameter
$z->SetCurrentValue( "teste" ); // hangs here

I saw this at some ASPX foruns... no idea why it doesn't work here on PHP... feedback would be highly appreciated.

[1] http://support.businessobjects.com/library/kbase/articles/c2018734.asp
djogopatrao at gmail dot com
16-Mar-2006 06:34
This function converts the crystal report in file $my_report to a PDF file $my_pdf. Exceptions may raise, so put it in a try..catch block.

I struggled so hard to get this done... any comments, please contact me.

function exportCrystalReportToPDF( $my_report, $my_pdf )
{
  // by dfcp/mar/06
  $ObjectFactory= New COM("CrystalReports11.ObjectFactory.1");
  $crapp = $ObjectFactory->CreateObject("CrystalDesignRunTime.Application");
  $creport = $crapp->OpenReport($my_report, 1);

  $creport->ExportOptions->DiskFileName=$my_pdf;
  $creport->ExportOptions->PDFExportAllPages=true;
  $creport->ExportOptions->DestinationType=1; // Export to File
  $creport->ExportOptions->FormatType=31; // Type: PDF
  $creport->Export(false);
}
a dot kulikov at pool4tool dot com
13-Mar-2006 09:36
In case you are wondering how to group rows or columns in the freshly created EXCEL files, then this may help you

<?
   /***
    * Grouping Rows optically in Excel Using a COM Object
    *
    * That was not easy, I have spent several hours of trial and error to get
    * this thing to work!!!
    *
    * @author Kulikov Alexey <a.kulikov@gmail.com>
    * @since  13.03.2006
    *
    * @see    Open Excel, Hit Alt+F11, thne Hit F2 -- this is your COM bible
    ***/

   //starting excel
   $excel = new COM("excel.application") or die("Unable to instanciate excel");
   print "Loaded excel, version {$excel->Version}\n";

   //bring it to front
   #$excel->Visible = 1;//NOT

   //dont want alerts ... run silent
   $excel->DisplayAlerts = 0;

   //create a new workbook
   $wkb = $excel->Workbooks->Add();

   //select the default sheet
   $sheet=$wkb->Worksheets(1);

   //make it the active sheet
   $sheet->activate;

   //fill it with some bogus data
   for($row=1;$row<=7;$row++){
       for ($col=1;$col<=5;$col++){

          $sheet->activate;
          $cell=$sheet->Cells($row,$col);
          $cell->Activate;
          $cell->value = 'pool4tool 4eva ' . $row . ' ' . $col . ' ak';
       }//end of colcount for loop
   }

   ///////////
   // Select Rows 2 to 5
   $r = $sheet->Range("2:5")->Rows;

   // group them baby, yeah
   $r->Cells->Group;

   // save the new file
   $strPath = 'tfile.xls';
   if (file_exists($strPath)) {unlink($strPath);}
   $wkb->SaveAs($strPath);

   //close the book
   $wkb->Close(false);
   $excel->Workbooks->Close();

   //free up the RAM
   unset($sheet);

   //closing excel
   $excel->Quit();

   //free the object
   $excel = null;
?>
M.F.
08-Mar-2006 12:06
I couldn't find much on Crystal Reports and COM's when I went to tackle it
so I thought a few lines of code here may help out anyone looking for where
to get started in the future.
 
$crapp = new COM("CrystalRuntime.Application.10");
$creport = $crapp->OpenReport($reportToRun, 1);
//reportToRun=full path to *.rpt file

$creport->Database->Tables->
Item(1)->ConnectionProperties['User ID'] =  $user;

$creport->Database->Tables->
Item(1)->ConnectionProperties['Password'] = $pass;

//fomatType = integer 22=xls, 31=pdf etc
 $creport->ExportOptions->FormatType = $formatType;
   
//type 1 is to output to a file I think 2 is email
 $creport->ExportOptions->DestinationType = 1;
     
//location = full path to report output file
$creport->ExportOptions->DiskFileName = $location;
   
 $creport->DiscardSavedData();
 $creport->Export(False);
Pedro Heliodoro
05-Mar-2006 02:38
Using the Windows Media Player OCX and the latest snap of PHP 5.1 i was able to eject a CD-ROM drive

<?php
//create an instance of Windows Media Player
$mp = new COM("WMPlayer.OCX");
//ejects the first cd-rom on the drive list
$mp->cdromcollection->item(0)->eject();

?>
vedanta dot barooah at gmail dot com
29-Jan-2006 07:59
Microsoft provides two binaries to create windows services: INSTSRV.EXE and SRVANY.EXE, using these php scripts can be run as windows services.

More information is available at: http://support.microsoft.com/?kbid=137890
sadi at unicornsoftbd dot com
17-Nov-2005 04:18
There's no way to use static dlls in php. only way to use a dll in php is to make it a com object first and then using it in php like this

<?php
$NewCom
=new COM("uni.example");
?>

once we created the COM object this can be used like any other php classes.
                       sadi
                       www.unicornsoftbd.com
allan666 at gmail dot com
29-Sep-2005 03:37
If you are using a COM object that opens windows or dialogs (like Office applications), those windows or dialogs will not appear and will stay invisible even if you use codes like    

$word->visible = true;

To solve this problem, go to the web service properties (Administrative Tools) and click (in the Logon TAB) "Allow the Service to Iterate with desktop".

This explain lots of problems to close applications. When you try to close, the dialos asking to save the file must appear, but only in the option to iterate with desktop is on.

Hope it helps.
dazb@localhost
26-May-2005 01:53
For permissions problems, etc. including "Could Not Open Macro Storage" with Word;
How To Configure Office Applications to Run Under the Interactive User Account

http://support.microsoft.com/kb/288366/EN-US/
mpg123 at thinstall dot com
09-May-2005 01: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
// php translation of asp script by Bill Wooten from
// http://www.4guysfromrolla.com/webtech/082802-1.shtml
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";
    }
}

// Test the function:
showServices("", "Win32_Processor");
showServices("", "Win32_LogicalDisk");
angelo [at] mandato <dot> com
25-Apr-2005 09: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 05:47
Simple convert xls to csv
<?php
// starting excel
$excel = new COM("excel.application") or die("Unable to instanciate excel");
print
"Loaded excel, version {$excel->Version}\n";

//bring it to front
#$excel->Visible = 1;//NOT
//dont want alerts ... run silent
$excel->DisplayAlerts = 0;

//open  document
$excel->Workbooks->Open("C:\\mydir\\myfile.xls");
//XlFileFormat.xlcsv file format is 6
//saveas command (file,format ......)
$excel->Workbooks[1]->SaveAs("c:\\mydir\\myfile.csv",6);

//closing excel
$excel->Quit();

//free the object
$excel->Release();
$excel = null;
?>
Jack dot CHLiang at gmail dot com
10-Apr-2005 10: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

// The example of print out the result
$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>";

}

/**
 * @param $file string The excel file path
 * @param $keyword string The keyword
 * @param $result array The search result
 */

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 09: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 12: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 08: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 03:13
<?
//Connect Database
$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 09: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 02: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;            //                                'Width of the map in pixels
           
$mMap->Height   = 300;            //                                'Height of the map in pixels
           
$mMap->BackColor = 15130848;
           
$_SESSION['map'] = $mMap;
        }

   
$resultRefresh = $mMap->Refresh();                                //Refresh the map
   
$urlImage      = $mMap->GetImageAsUrl();
    print
"<br>urlImage=$urlImage<br>";

    print
"<br><IMG SRC='$urlImage'>";

/*
    $ArcIMSConnector->Release();
    $ArcIMSConnector = null;

    $mMap->Release();
    $mMap = null;
*/

?>
ferozzahid [at] usa [dot] com
24-Aug-2004 12: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 01: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 12: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 05: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..SCO