COM関数
参考
COM についてのより詳細な情報は » COM 仕様 を読みましょう。 PHP と COM の FAQ からも情報が得られるでしょう。 MS Office アプリケーションをサーバーサイドで使用しようと考えておられるなら、 » Considerations for Server-Side Automation of Office の情報も読んでおくべきでしょう。
目次
- com_create_guid — グローバルユニーク ID (GUID) を生成する
- com_event_sink — COM オブジェクトのイベントを PHP オブジェクトに接続する
- com_get_active_object — すでに実行中の COM オブジェクトのインスタンスへのハンドルを返す
- com_load_typelib — タイプライブラリを読み込む
- com_message_pump — COM メッセージを処理し、timeoutms ミリ秒の間待つ
- com_print_typeinfo — ディスパッチインターフェイスのために、PHP のクラス定義を出力する
- variant_abs — variant の絶対値を返す
- variant_add — 2 つの variant 値を「加算」し、結果を返す
- variant_and — 2 つの variant の論理積を計算し、結果を返す
- variant_cast — variant を、別の型の新しい variant に変換する
- variant_cat — 2 つの variant 値を連結し、その結果を返す
- variant_cmp — 2 つの variant を比較する
- variant_date_from_timestamp — Unix タイムスタンプを、日付形式の variant で返す
- variant_date_to_timestamp — 日付/時刻の variant 値を Unix タイムスタンプに変換する
- variant_div — 2 つの variant の除算結果を返す
- variant_eqv — 2 つの variant のビット値が等しいかどうかを調べる
- variant_fix — variant の整数部を返す
- variant_get_type — variant オブジェクトの型を返す
- variant_idiv — variants を整数に変換し、除算の結果を返す
- variant_imp — 2 つの variant のビット implication を行う
- variant_int — variant の整数部を返す
- variant_mod — 2 つの variant の除算を行い、剰余を返す
- variant_mul — 2 つの variant の乗算を行い、その結果を返す
- variant_neg — variant の論理否定演算を行う
- variant_not — variant のビット否定演算を行う
- variant_or — 2 つの variant の論理和を計算する
- variant_pow — 2 つの variant の累乗計算を行い、その結果を返す
- variant_round — 指定した桁で variant を丸める
- variant_set — variant オブジェクトに新しい値を代入する
- variant_set_type — variant を「その場で」別の型に変換する
- variant_sub — 左の variant から右の variant を引き、その結果を返す
- variant_xor — 2 つの variant の排他的論理和を計算する
+add a note
User Contributed Notes 31 notes
Sorin Negulescu ¶
8 years ago
I have spent a lot of hours trying to make word.application work on a Windows Server using Apache as a service.
The application was working if Apache was started from command line (not as a service).
In the hope that this will help others not to lose hours of trying to solve this problem here is what I found out:
- In php.ini make sure you have the following key under the [COM_DOT_NET]: extension=php_com_dotnet.dll
- Apache shall run under a normal user account (not SYSTEM account). Run services.msc and fill-in the info of the user under the Apache service's Properties tab.
- Make sure you are able to start MS Word normally under that user account and dismiss all the dialogs that may appear (license, your info with initials, etc.). Start Word once again and make sure no dialogs appear.
- Launch dcomcnfg.exe->Console Root->Component Services->Computers->My Computer->DCOM Config->Microsoft Office Word 97 - 2003->Right Click(Properties)->Identity Tab and fill in the same user account information as for Apache service.
- If you cannot find the Microsoft Office Word 97 - 2003, make sure you are launching the correct DCOM Config (64 bit vs 32 bit) depending on what version of Office you have installed. To launch the 32 bit version run: mmc comexp.msc /32
Before following the steps described above, the winword.exe app appears in task manager but, if you look at the memory consumption you can notice two things:
- it increases slowly
- it stops usually at about 7-8 MB.
Keywords: COM, word.application, Apache, service, winword, timeout, no error
tomas dot pacl at atlas dot cz ¶
21 years ago
Passing parameters by reference in PHP 4.3.2 (and in a future releases of PHP )
In PHP 4.3.2 allow_call_time_pass_reference option is set to "Off" by default and future versions may not support this option any longer.
Some COM functions has by-reference parameters. VARIANT object must be used to call this functions, but it would be passed without an '&' before variable name.
Example:
<?php
$myStringVariant = new VARIANT("over-write me", VT_BSTR);
/* works */
$result = $comobj->DoSomethingTo($myStringVariant );
/* works only with allow_call_time_pass_reference option set to "On" and may not work in a future release of PHP */
$result = $comobj->DoSomethingTo(&$myStringVariant );
/* The value in the variant can be retrieved by: */
$theActualValue = $myStringVariant->value;
?>
tomfmason at nospam-gmail dot com ¶
17 years ago
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
ferozzahid [at] usa [dot] com ¶
20 years ago
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:
<?php
$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
Francois-R dot Boyer at PolyMtl dot ca ¶
17 years ago
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', '...');
?>
naveed at php dot net ¶
17 years ago
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);
?>
alanraycom at el hogar dot net com ¶
21 years ago
XSLT transformations using MSXML can be done with this code
<?php
function xsltransform1($xslpath,$xmlstring)
{
$xml= new COM("Microsoft.XMLDOM");
$xml->async=false;
// $xmlstring is an xml string
$xml->load($xmlstring);
$xsl = new COM("Microsoft.XMLDOM");
$xsl->async=false;
// $xslpath is path to an xsl file
$xsl->load($xslpath);
$response=$xml->transformNode($xsl);
unset($xml);
unset($xsl);
return $response;
}
?>
enjoy
Alan Young
madon at cma-it dot com ¶
22 years ago
I thought this excel chart example could be useful.
Note the use of Excel.application vs Excel.sheet.
<pre>
<?php
print "Hi";
#Instantiate the spreadsheet component.
# $ex = new COM("Excel.sheet") or Die ("Did not connect");
$exapp = new COM("Excel.application") or Die ("Did not connect");
#Get the application name and version
print "Application name:{$ex->Application->value}<BR>" ;
print "Loaded version: {$ex->Application->version}<BR>";
$wkb=$exapp->Workbooks->add();
#$wkb = $ex->Application->ActiveWorkbook or Die ("Did not open workbook");
print "we opened workbook<BR>";
$ex->Application->Visible = 1; #Make Excel visible.
print "we made excell visible<BR>";
$sheets = $wkb->Worksheets(1); #Select the sheet
print "selected a sheet<BR>";
$sheets->activate; #Activate it
print "activated sheet<BR>";
#This is a new sheet
$sheets2 = $wkb->Worksheets->add(); #Add a sheet
print "added a new sheet<BR>";
$sheets2->activate; #Activate it
print "activated sheet<BR>";
$sheets2->name="Report Second page";
$sheets->name="Report First page";
print "We set a name to the sheet: $sheets->name<BR>";
# fills a columns
$maxi=20;
for ($i=1;$i<$maxi;$i++) {
$cell = $sheets->Cells($i,5) ; #Select the cell (Row Column number)
$cell->activate; #Activate the cell
$cell->value = $i*$i; #Change it to 15000
}
$ch = $sheets->chartobjects->add(50, 40, 400, 100); # make a chartobject
$chartje = $ch->chart; # place a chart in the chart object
$chartje->activate; #activate chartobject
$chartje->ChartType=63;
$selected = $sheets->range("E1:E$maxi"); # set the data the chart uses
$chartje->setsourcedata($selected); # set the data the chart uses
print "set the data the chart uses <BR>";
$file_name="D:/apache/Apache/htdocs/alm/tmp/final14.xls";
if (file_exists($file_name)) {unlink($file_name);}
#$ex->Application->ActiveWorkbook->SaveAs($file_name); # saves sheet as final.xls
$wkb->SaveAs($file_name); # saves sheet as final.xls
print "saved<BR>";
#$ex->Application->ActiveWorkbook->Close("False");
$exapp->Quit();
unset($exapp);
?>
</pre>
Alex Madon
Anonymous ¶
18 years ago
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.
a dot kulikov at pool4tool dot com ¶
18 years ago
In case you are wondering how to group rows or columns in the freshly created EXCEL files, then this may help you
<?php
/***
* 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;
?>