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);
?>
XV. COM と .Net (Windows)
導入
COM は Component Object Model の略語であり、 DCE RPC (オープンスタンダード) の最上位のオブジェクト指向レイヤーです。 COM はコール手順を共通化し、あらゆる言語でコードを記述し、 (COM に対応した)他の言語で書かれたコードをコール、相互運用することを可能にします。 あらゆる言語で書くことを可能にするだけではなく、 同じ実行形式の一部となることすら不要です。 コードは、同じマシンで実行される他のプロセスのコードである DLL からロードしたり、 または、リモートマシン上の他のプロセスにあるコードを DCOM (分散 COM) で 利用することができます。 この場合、コードの中では、コンポーネントの存在する場所を意識する必要はありません。
OLE オートメーションと呼ばれる COM のサブセットがあります。 これは、COM オブジェクトに祖な結合を行うことができる COM インターフェイスを 提供します。これにより、コンパイル時にオブジェクトの動作を知ることなく、 実行時にコールを行うことができるようになります。 PHP COM 拡張モジュールは、OLE オートメーションを使用して スクリプトから互換性のあるオブジェクトを作成/コールすることができます。 技術的に述べると、 全ての COM オブジェクトが OLE 互換であるというわけではないため、 実際には、この拡張モジュールは "PHP の OLE オートメーション 拡張モジュール" と呼ばれるべきものです。
ところで、なぜ COM を使用する必要があるのでしょう? COM は、 Windows 環境でアプリケーションとコンポーネントを結び付ける代表的な手法の一つで、 COM を使用して Microsoft Word を起動し、 ドキュメントテンプレートを埋めて、Word 文書として結果を保存し、Web サイトの 訪問者に送信することができます。 また COM を使用して、ネットワークの管理タスクを処理したり IIS を設定したりすることができます。これらは最も一般的な使用法にすぎません。 COM でできることはまだまだたくさんあります。
PHP 5 以降、この拡張モジュール(とこの文書)は最初から書き直され、 古い紛らわしい部分は削除されました。さらに Microsoft により提供された COM との相互運用レイヤーを用いて .Net アセンブリのインスタンス化と生成をサポートしました。
PHP 5 におけるこの拡張モジュールの変更点の概要については、 » この文章 を参照してください。
要件
COM 関数は、Windows 版の PHP でのみ利用可能です。
.Net サポートは、PHP 5 と .Net ランタイムを必要とします。
インストール手順
PHP コアに含まれるため、 追加のインストール無しで使用できます。
Windows 版の PHP には この拡張モジュールのサポートが組み込まれています。これらの関数を使用 するために拡張モジュールを追加でロードする必要はありません。
あなたには、(MS Word のような)使用する様々な COM オブジェクトのインストールを正しく 行っておく責任があります。 PHP にこれら全てをバンドルすることはできません。
foreach
PHP 5 以降、標準的な COM/OLE IEnumVariant の内容について、 PHP の foreach 命令を使用した反復処理を行うことができます。分かりやすく言うと、 これは、VB/ASP のコードで For Each を使用できる場所には foreach を使用できるということを意味します。
例 393. ASP における For Each
<%
Set domainObject = GetObject("WinNT://Domain")
For Each obj in domainObject
Response.Write obj.Name & "<br />"
Next
%>
例 394. PHP 4 におけるwhile() ... Next()
<?php
$domainObject = new COM("WinNT://Domain");
while ($obj = $domainObject->Next()) {
echo $obj->Name . "<br />";
}
?>
例 395. PHP 5 における foreach
<?php
$domainObject = new COM("WinNT://Domain");
foreach ($domainObject as $obj) {
echo $obj->Name . "<br />";
}
?>
配列と配列形式の COM プロパティ
多くの COM オブジェクトは、プロパティを配列で公開したり 配列形式を使用してアクセスできるようにしています。 PHP 4 では、PHP の配列構文を使用してこれらのプロパティに対する読み書きが できますが、1 次元の配列のみがサポートされます。多次元のプロパティを 読み込みたい場合は、プロパティへのアクセスを関数コールに組み込んで 各パラメータを入れtうの各次元に対応させるという方法が可能ですが、 そのようなプロパティに対する書き込みの手段はありません。
PHP 5 では以下の新機能を用いることで多少ましになりました。
例外 (PHP 5)
COM から致命的なエラーが報告された場合、この拡張モジュールは com_exception クラスのインスタンスをスローします。 すべての COM 例外は code という定義済みの プロパティを保持しており、これは COM 操作が返す HRESULT 値に対応します。 プログラム上での例外の処理方法を決定するために、この値を使用する ことができます。
実行時設定
php.ini の設定により動作が変化します。
表 25. COM 設定オプション
| 名前 | デフォルト | 変更の範囲 | 変更履歴 |
|---|---|---|---|
| com.allow_dcom | "0" | PHP_INI_SYSTEM | PHP 4.0.5 以降で使用可能です。 |
| com.autoregister_typelib | "0" | PHP_INI_ALL | PHP 4 では PHP_INI_SYSTEM です。PHP 4.1.0 以降で使用可能です。 |
| com.autoregister_verbose | "0" | PHP_INI_ALL | PHP 4 では PHP_INI_SYSTEM です。PHP 4.1.0 以降で使用可能です。 |
| com.autoregister_casesensitive | "1" | PHP_INI_ALL | PHP 4 では PHP_INI_SYSTEM です。PHP 4.1.0 以降で使用可能です。 |
| com.code_page | "" | PHP_INI_ALL | PHP 5.0.0 以降で使用可能です。 |
| com.typelib_file | "" | PHP_INI_SYSTEM | PHP 4.0.5 以降で使用可能です。 |
PHP_INI_* 定数の詳細および定義については 付録 I. php.ini ディレクティブ を参照してください。
以下に設定ディレクティブに関する 簡単な説明を示します。
- com.allow_dcom
これを on にすると、PHP が D-COM (分散 COM) クライアントとして動作することを許可し、 PHP スクリプトがリモートサーバ上に COM オブジェクトを生成することを 許可します。
- com.autoregister_typelib
これを on にすると、生成したオブジェクトのタイプライブラリから取得した 定数を PHP に登録しようと試みます。ただし、それはオブジェクトが 当該情報を取得するためのインターフェースを提供している場合のみです。 登録する定数の大文字小文字を区別するかどうかについては、 com.autoregister_casesensitive 設定ディレクティブで 制御します。
- com.autoregister_verbose
これを on にすると、オブジェクト生成時のタイプライブラリの読み込み中に 発生したすべての問題が PHP のエラー機構を用いて報告されます。 デフォルトは off で、この場合はタイプライブラリの検索や読み込みの際の エラーは一切報告されません。
- com.autoregister_casesensitive
これを on にすると (デフォルト)、自動読み込みされた タイプライブラリ中に見つかった定数が、大文字小文字を区別して 登録されます。詳細は com_load_typelib() を参照ください。
- com.code_page
これは、COM オブジェクトとの文字列の受け渡しに使用するデフォルトの 文字セットコードページを制御します。空の文字列が設定された場合、 PHP は CP_ACP が指定されたと仮定します。 これは、デフォルトのシステム ANSI コードページです。
スクリプト中のテキストがデフォルトとは異なるエンコーディング/ 文字セットを使用している場合、このディレクティブを設定することで COM クラスのコンストラクタのパラメータとして コードページを指定する必要がなくなります。 (他の PHP 設定ディレクティブとともに) このディレクティブを使用すると、 PHP スクリプトの移植可能性が悪くなることに注意しましょう。 できる限り、COM のコンストラクタにパラメータを指定する方式をとるべきです。
注意: この設定ディレクティブは PHP 5 以降で使用可能です。
- com.typelib_file
このパラメータでは、起動時に読み込まれるタイプライブラリの一覧を 含むファイルへのパスを保持します。このファイル内の各行が タイプライブラリ名として扱われ、com_load_typelib() をコールした際にそれが読み込まれます。登録された定数は永続的に 保持されるので、ライブラリの読み込みは一度だけでよくなります。 タイプライブラリの名前が #cis あるいは #case_insensitive で終わる場合は、そのライブラリから 読み込まれた定数は大文字小文字を区別せずに登録されます。
リソース型
この拡張モジュールでは、COM コンポーネントへの参照を定義しています。 これは、非推奨の com_load() 関数が返すものです (この関数は PHP 5 には存在しません。かわりに COM クラスを使用します)。
定義済み定数
以下の定数が定義されています。 この関数の拡張モジュールが 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)
参考
COM についてのより詳細な情報は » COM 仕様 を読むか、あるいは Don Box の » Yet Another COM Library (YACL) をごらんください。その他の有用な情報が、 章 57. PHP と COM の FAQ からも得られるでしょう。 MS Office アプリケーションをサーバサイドで使用しようと考えておられるなら、 » Considerations for Server-Side Automation of Office の情報も読んでおくべきでしょう。
目次
- COM — COM クラス
- DOTNET — DOTNET クラス
- VARIANT — VARIANT クラス
- com_addref — コンポーネントの参照カウンタを増やす [非推奨]
- com_create_guid — グローバルユニーク ID (GUID) を生成する
- com_event_sink — COM オブジェクトのイベントを PHP オブジェクトに接続する
- com_get_active_object — すでに実行中の COM オブジェクトのインスタンスへのハンドルを返す
- com_get — COM コンポーネントのプロパティの値を得る [非推奨]
- com_invoke — COM コンポーネントのメソッドをコールする [非推奨]
- com_isenum — COM オブジェクトが IEnumVariant インターフェースを実装しているかどうかを 示す [非推奨]
- com_load_typelib — タイプライブラリを読み込む
- com_load — COM コンポーネントへの新規リファレンスを作成する [非推奨]
- com_message_pump — COM メッセージを処理し、timeoutms ミリ秒の間待つ
- com_print_typeinfo — ディスパッチインターフェースのために、PHP のクラス定義を出力する
- com_propget — com_get() のエイリアス
- com_propput — com_set() のエイリアス
- com_propset — com_set() のエイリアス
- com_release — コンポーネントリファレンスカウンタを減らす [廃止]
- com_set — COM コンポーネントのプロパティに値を代入する
- 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_type — variant を「その場で」別の型に変換する
- variant_set — variant オブジェクトに新しい値を代入する
- variant_sub — 左の variant から右の variant を引き、その結果を返す
- variant_xor — 2 つの variant の排他的論理和を計算する
COM と .Net (Windows)
10-Mar-2007 10:24
14-Feb-2007 01: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 …);
?>
06-Feb-2007 05: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.....
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.
18-Jul-2006 10: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");
23-Mar-2006 03: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
16-Mar-2006 11: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);
}
14-Mar-2006 02: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;
?>
08-Mar-2006 05: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);
06-Mar-2006 07: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();
?>
30-Jan-2006 12: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
17-Nov-2005 09: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
29-Sep-2005 07: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.
26-May-2005 05: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/
10-May-2005 05: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");
26-Apr-2005 01: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.
24-Apr-2005 09: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;
?>
11-Apr-2005 02: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
14-Mar-2005 02: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');
24-Feb-2005 05: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.
14-Feb-2005 01: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
11-Feb-2005 08: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()"
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
26-Sep-2004 06: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;
*/
?>
24-Aug-2004 04: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
11-Aug-2004 05: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!
22-Jul-2004 04: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.
13-Jul-2004 09: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.
21-Jun-2004 09: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
04-Jun-2004 03: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
// msword.inc.php
// 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
$wdFormatDocument = 0;
$wdFormatTemplate = 1;
$wdFormatText = 2;
$wdFormatTextLineBreaks = 3;
$wdFormatDOSText = 4;
$wdFormatDOSTextLineBreaks = 5;
$wdFormatRTF = 6;
$wdFormatUnicodeText = 7;
$wdFormatHTML=8;
class MSWord
{
// Vars:
var $handle;
// Create COM instance to word
function MSWord($Visible = false)
{
$this->handle = new COM("word.application") or die("Unable to instanciate Word");
$this->handle->Visible = $Visible;
}
// Open existing document
function Open($File)
{
$this->handle->Documents->Open($File);
}
// Create new document
function NewDocument()
{
$this->handle->Documents->Add();
}
// Write text to active document
function WriteText( $Text )
{
$this->handle->Selection->Typetext( $Text );
}
// Number of documents open
function DocumentCount()
{
return $this->handle->Documents->Count;
}
// Save document as another file and/or format
function SaveAs($File, $Format = 0 )
{
$this->handle->ActiveDocument->SaveAs($File, $Format);
}
// Save active document
function Save()
{
$this->handle->ActiveDocument->Save();
}
// close active document.
function Close()
{
$this->handle->ActiveDocument->Close();
}
// Get word version
function GetVersion()
{
return $this->handle->Version;
}
// get handle to word
function GetHandle()
{
return $this->handle;
}
// Clean up instance with word
function Quit()
{
if( $this->handle )
{
// close word
$this->handle->Quit();
// free the object
$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();
?>
19-May-2004 08:30
Useful PHP functions I created (similar to other standard PHP database functions) for working with an ADO datasource:
<?php
// ado.inc.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 ) // Defined in adoint.h - adBookmarkFirst = 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);
}
// Extra functions:
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.
11-May-2004 08: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
05-Apr-2004 09: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(); // Call the "hello()" method
echo $output; // Displays Hello World! (so this comes from the dll!)
?>
01-Mar-2004 01: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.
13-Feb-2004 08: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
16-Dec-2003 04: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) ;
?>
16-Dec-2003 02: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 = $ADSI->OpenDsObject("LDAP://DC=mydomain,DC=com",
"DOMAIN\login",
"password",
515) ;
while($Obj = $DsObj->Next())
{
echo $Obj->name.' with class of: '.$Obj->class.'<br>' ;
}
?>
The access type enumeration you can use as ADS_AUTHENTICATION_ENUM.
07-Dec-2003 07:42
After many hours of trial and error, I have finally discovered how to kill the notorious Word process. I hope my solution works for everyone else.
#1) $word->Quit() is perfectly fine. Don't bother feeding in as parameter those empty variants.
#2) Do NOT have com_load_typelib('Word.Application') anywhere in your script.
#3) Make sure you have the following line before $word->Quit() :
$word->Documents[1]->Close(false);
#4) Add the following lines after $word->Quit() :
$word->Release();
$word = null;
unset($word);
If my solution indeed helped you with your problem, please email me and let me know. I would like to see if the problem was indeed solved.
05-Dec-2003 01:07
Yes !
Finally i found how to kill MsWord Com process...
The next MSWord function does not work if the optional args are empty :
this doesn't work:
$word->Quit();
but this is ok :
$empty = new VARIANT(); //for optional args...
$word->Quit($empty,$empty,$empty);
Hope this usefull.
Aldric
04-Dec-2003 08:50
XSLT transformations using MSXML can be done with this code
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
02-Dec-2003 09:19
Many COM objects don't do well when passing long (win32) filenames as function parameters. You can get the 8.3 name of the folder or file on *most* (some win platforms don't support it, and it can be toggled off in the registry for performance reasons) servers using the following:
<?php
//create FSO instance
$exFSO = new COM("Scripting.FileSystemObject") or die ("Could not create Scripting.FileSystemObject");
//set vars
$myDir = "C:\\Program Files\\";
$myFile = "a long file name.txt";
//get folder & file objects
$exDir = $exFSO->GetFolder($myDir);
$exFile = $exFSO->GetFile($myDir . $myFile);
echo $exDir->ShortPath;
echo $exFile->ShortPath;
?>
Here is an example of reading the custom properties like Author, Keywords, etc. which are stored in MS Office and other Windows files. You must install and register dsofile as described at http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q224351. The .frm file in that distribution lists most of the available properties.
// the file you wish to access
$fn = '/docs/MFA.xls';
$oFilePropReader = new COM('DSOleFile.PropertyReader');
$props = $oFilePropReader->GetDocumentProperties($fn);
// one syntax
$au = com_get($props, 'Author');
print "au: $au \n";
//another syntax
$str = 'LastEditedBy';
$lsb = $props->$str;
var_dump($lsb);
// set a property if you wish
if (!$props->IsReadOnly()) {
$props->Subject = 'tlc';
}
17-Nov-2003 10:17
How to send email via MAPI (works with Windows NT4, apache launched as a service)
#New MAPI session...
$session = new COM("MAPI.Session");
#Login
$strProfileInfo = "exchange_server" . chr(10) . "exchange_user";
$session->Logon("", "", 0, 1, 0, 1, $strProfileInfo);
# New message...
$msg = $session->Outbox->Messages->Add();
$msg->Subject = "Subject";
$msg->Text = "body";
#set recipients...
$rcpts = $msg->Recipients;
$rcpts->AddMultiple("toto@toto.com", 1); #To...
$rcpts->AddMultiple("titi@titi.com", 2); #Cc...
$rcpts->AddMultiple("tutu@tutu.com", 3); #Bcc...
# Resolve senders
$rcpts->Resolve();
#Send message
$msg->Send();
#Logoff
$session->Logoff();
#Cleanup
if($msg!=null) {
$msg->Release();
$msg = null;
}
if($session!=null) {
$session->Release();
$session = null;
}
ps : NT account launching the service and exchange user must match !
12-Nov-2003 12:45
Apache 1.3
PHP 4.x
I found the Example from Admin Purplerain usefull but, it wasn't working without this first Line:
com_load_typelib('Outlook.Application');
// after that the code from Purplerain
$objApp = new COM("Outlook.Application");
$myItem = $objApp->CreateItem(olMailItem);
$a=$myItem->Recipients->Add("your adress here");
$myItem->Subject="Subject";
$myItem->Body="This is a Body Section now.....!";
$myItem->Display();
$myItem->Send();
Still have to switch of the Outlook Security Warnings.
RE: PROBLEM QUITTING MICROSOFT EXCEL
I strongly suspect this is due to excel helpfully asking "Do you want to save the changes you made to 'Book1'?" when Quit is called.
This can be avoided by making sure that you set the 'Saved' property to True on ALL workbooks before exiting.
Assuming you only have the one workbook:
$excel->ActiveWorkbook->Saved = 1
Word suffers a similar problem and you must set the saved property to true on each document.
This demonstrates the pitfalls of scripting Word, Excel and similar applications in a non-interactive environment.
07-Nov-2003 01:07
Hi,
I�ve GOOGLED alot to find out how to use the MS Index Server (which comes with IIS-Webserver) as a search engine. Here is the code that makes a connection via ADO and lists a result for a given searchstring. Hope you'll find it usefull, it will surely prevent you from searching a long time in search engines. If anybody knows how to do it better, feel free to post it here. The following url contains a description for the index server. It also mentions some further features of the index server (http://www.jiafangyifang.com/memo.php?ID=3232 japanese only, sorry).
$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) //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();
}
04-Nov-2003 05:13
PROBLEM QUITTING MICROSOFT EXCEL
I have been trying to solve the problem of terminating the excel process when using the COM functionality. I found a few 'supposed fixes' including not using arrays etc but none of them seemed to work. Example:
$excel->application->Quit();
$excel->Quit();
None of these variants properly quit the process - ONLY the visible application. Several hours of using your code would leave thousands of excel processes running invisibly in the background and eating all your ram very quickly.
As I was developing on a solution designed to work on clients running windows, my solution was to install microsofts 'kill.exe' into the windows directory and then run it using:
shell_exec("kill excel.exe");
One problem is because kill.exe is an add on utility, some clients running windows will not have it. The solution is then to use file_exists(filename) to detect for the file and then if not present, let the user download it. Example:
$killApp = "C:\WINDOWS\KILL.EXE";
if (file_exists($killApp)) {
# continue
} else {
# show message and link to kill.exe download
}
11-Oct-2003 09:46
-- Catching COM events --
Hello everyone.
Anyone who did VB + COM would know something is missing here: events!
Here's how to catch IE events using some undocumented functions:
----------
class ieSinker {
var $terminated = false;
function TitleChange($text) {
echo("title has changed: $test \n");
}
function OnQuit() {
echo "Quit!\n";
$this->terminated = true;
}
}
$ie = new COM("InternetExplorer.Application");
$ieSink =& new ieSinker();
com_event_sink($ie, $ieSink, "DWebBrowserEvents2");
$ie->navigate(' PATH TO YOUR HTML FILE GOES HERE! ');
$ie->visible = True;
while(!$ieSink->terminated) {
com_message_pump(10);
}
----------
Works perfect for me with php 4.3
You can find more info on the undocumented functions in the YACL documentation.
Note the "DWebBrowserEvents2" interface. You can find more information about these in the microsoft platform SDK documentation, under "web development". Or maybe they have a smaller web development SDK? I wasn't able to use any other interface, so what I do is send messages from IE to the PHP script by changing the title of the html document with JavaScript.
By the way, I cant take credit for the above code, I stole it from some website of which I lost the address.
Thats it... bye...
Convert Microsoft word document .DOC to adobe acrobat .PS or .PDF files:
Drawback: if any dialog boxes pop up, the conversion will become non-automated.
<?
// You must have word and adobe acrobat distiller on
// your system, although theoretically any printer driver
// that makes .PS files would work.
// 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;
// Select the acrobat distiller as the active printer.
// I presume that you could also use the Acrobat PDF writer // driver that comes with Acrobat full version.
$word->ActivePrinter = "Acrobat Distiller";
// Open a word document, or anything else that word
// can read
$word->Documents->Open($input);
// This will create a .PS file called $output
$word->ActiveDocument->PrintOut(0, 0, 0, $output);
// If you need a .pdf instead, use the acrobat
// distiller's watched folder option.
// closing word
$word->Quit();
// free the object
$word->Release();
$word = null;
?>
26-Sep-2003 09:24
took me a while until I found out how to loop through COM objects in PHP.... in ASP, you use something like:
<%
set domainObject = GetObject("WinNT://Domain")
for each obj in domainObject
Response.write obj.Name & "<br>"
next
%>
I finally found a note in a PHP bogus bug report that said you needed to do something like this (this is using ADSI):
<?php
$adsi = new COM("WinNT://Domain");
while($obj = $adsi->Next()) {
echo $obj->Name.'<br>';
}// while
// will list all the names of all objects in the domain 'Domain'
?>
Also, you can access the IIS metabase by doing something like the following:
<?php
$iis = new COM("IIS://localhost/w3svc");
while($obj = $iis->Next()) {
if ($obj->Class == 'IISWebServer') {
$site = new COM("IIS://Localhost/w3svc/".$obj->Name);
echo 'serviceID ('.$obj->Name.'): '.$site->ServerComment.'<br>';
$bindings = $site->ServerBindings;
echo '<ul>';
foreach($bindings as $binding) {
list($ip, $port, $hostHeader) = explode(':', $binding);
echo "<li>$ip:$port -- $hostHeader</li>";
}// foreach
echo '</ul>';
// hint: ssl bindings are in $site->SecureBindings
unset($site);
}// if
}// while
unset($iis);
// will list all the sites and their bindings on 'localhost'
?>
23-Sep-2003 01:35
Took me a while to work this out as there is very little help available. Accessing com variables that are multi arrays can prove tricky.
e.g.
$ex = new COM("application");
$ex->Stock->stSalesBands
is an array A-H [stPrice,stCurrency]
php chucks out an error on this:
$ex->Stock->stSalesBands(C)->stPrice;
so, you have to do this
$tmp = $ex->Stock->stSalesBands(C);
echo $tmp->stPrice;
unset($tmp)
07-Sep-2003 05:17
This took me days to work out how to do so I gotta share it:
How to get the word count from a MS Word Document:
#Instantiate the Word component.
$word = new COM("word.application") or die("Unable to instantiate Word");
$word->Visible = 1;
$word->Documents->Open("c:/anydocument.doc");
$temp = $word->Dialogs->Item(228);
$temp->Execute();
$numwords = $temp->Words();
echo $numwords;
$word->Quit();
Note that this is the only way to get the word count accurately:
$word->ActiveDocument->Words->Count;
Will see all carriage returns and punctuation as words so is wildy innaccurate.
12-Jul-2003 07:36
open PDF Documents with Internet Explorer
$browser = new COM("InternetExplorer.Application");
$browser->Visible = true;
$browser->Navigate("path_to_your_pdf_document");
this works for me with php-gtk
16-Jun-2003 10:07
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:
$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;
23-Mar-2003 10:47
PASSING/RETURNING PARAMETERS BY REFERENCE
=========================================
Some COM functions not only return values through the return value, but also act upon a variable passed to it as a parameter *By Reference*:
RetVal = DoSomethingTo (myVariable)
Simply sticking an '&' in front of myVariable doesn't work - you need to pass it a variant of the correct type, as follows:
$myStringVariant = new VARIANT("over-write me", VT_BSTR);
$result = $comobj->DoSomethingTo( &$myStringVariant );
The value in the variant can then be retrieved by:
$theActualValue = $myStringVariant->value;
Other types of variant can be created as your needs demand - see the preceding section on the VARIANT type.
05-Mar-2003 07:55
To manage the Windows Register at HKEY_LOCAL_MACHINE\SOFTWARE\ use these functions:
<?php
/**
* @return string
* @param aplicacio string
* @param nom string
* @desc Retorna el valor del registre HKEY_LOCAL_MACHINE\SOFTWARE\aplicacio\nom
*/
function rtv_registre($aplicacio, $nom)
{
Global $WshShell;
$registre = "HKEY_LOCAL_MACHINE\SOFTWARE\\" . $aplicacio . "\\" . $nom;
$valor = $WshShell->RegRead($registre);
return($valor);
}
/**
* @return string
* @param aplicacio string
* @param nom string
* @param valor string
* @param tipus string
* @desc Actualitza el valor del registre HKEY_LOCAL_MACHINE\SOFTWARE\aplicacio\nom
*/
function put_registre($aplicacio, $nom, $valor, $tipus="REG_SZ")
{
Global $WshShell;
$registre = "HKEY_LOCAL_MACHINE\SOFTWARE\\" . $aplicacio . "\\" . $nom;
$retorn = $WshShell->RegWrite($registre, $valor, $tipus);
return($retorn);
}
//
// Creem una inst�ncia del COM que ens serveix per
// accedir al registre de Windows, i la mantenim.
// D'aquesta manera millorem el rendiment.
$WshShell = new COM("WScript.Shell");
?>
26-Feb-2003 10:51
With thanks to Harald Radi and Wez Furlong.
Some VBA functions have optional parameters. Sometimes the parameters you want to pass are not consecutive.
e.g.
GoTo What:=wdGoToBookmark, Name="BookMarkName"
GoTo(wdGoToBookmark,,,"BookMarkName)
In PHP, the "blank" parameters need to be empty.
Which is ...
<?php
// Some servers may have an auto timeout, so take as long as you want.
set_time_limit(0);
// Show all errors, warnings and notices whilst developing.
error_reporting(E_ALL);
// Used as a placeholder in certain COM functions where no parameter is required.
$empty = new VARIANT();
// Load the appropriate type library.
com_load_typelib('Word.Application');
// Create an object to use.
$word = new COM('word.application') or die('Unable to load Word');
print "Loaded Word, version {$word->Version}\n";
// Open a new document with bookmarks of YourName and YourAge.
$word->Documents->Open('C:/Unfilled.DOC');
// Fill in the information from the form.
$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourName'); // Note use of wdGoToBookmark, from the typelibrary and the use of $empty.
$word->Selection->TypeText($_GET['YourName']);
$word->Selection->GoTo(wdGoToBookmark,$empty,$empty,'YourAge');
$word->Selection->TypeText($_GET['YourAge']);
// Save it, close word and finish.
$word->Documents[1]->SaveAs("C:/{$_GET['YourName']}.doc");
$word->Quit();
$word->Release();
$word = null;
print "Word closed.\n";
?>
The example document is ...
Hello [Bookmark of YourName], you are [Bookmark of YourAge] years old.
and it would be called ...
word.php?YourName=Richard%20Quadling&YourAge=35
Regards,
Richard.
12-Dec-2002 04:23
Searched for days on how to set up a multi-column html output grid that didn't use an array when creating an ADODB connection. Couldn't find one so I figured it out myself. Pretty simple. Wish I would have tried it myself sooner. Commented code with database connection is below...
<html>
<body>
<table>
<?php
//create the database connection
$conn = new COM("ADODB.Connection");
$dsn = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . realpath("mydb.mdb");
$conn->Open($dsn);
//pull the data through SQL string
$rs = $conn->Execute("select clients from web");
$clients = $rs->Fields(1);
//start the multicolumn data output
$i = 0;
$columns = 5;
while (!$rs->EOF){
//if $i equals 0, start a row
if($i == 0){
echo "<tr>";
}
//then start writing the cells in the row, increase $i by one, and move to the next record
echo "<td>" . $clients->value . "</td>";
$i++;
$rs->movenext();
//once $i increments to equal $columns, end the row,
//and start the process over by setting $i to 0
if($i == $columns || $rs->EOF) {
echo "</tr>";
$i = 0;
}
}
//end multicolumn data output
//close the ADO connections and release resources
$rs->Close();
$conn->Close();
$rs = null;
$conn = null; ?>
</table>
</body>
</html>
27-Sep-2002 01:52
The documentation for this feature is a bit redundant. It mentions that COM performs and encourages information hiding (a.k.a. encapsulation) three times. Perhaps instead it could expand a bit on what COM is useful for, and particularly why combining it with PHP can be beneficial.
The contributed examples above do a nice job of illustrating the benefits of PHP+COM. In a nutshell, many Windows applications (especially office suites and databases) expose useful functionality through the COM interface.
For example, Microsoft Word can read RTF files and (of course) write Word Documents. You could use PHP to generate RTF and then use Microsoft Word via PHP's COM interface to convert the RTF to a DOC. The amazing thing about this is that you can actually insert PHP (or template) code into Word itself, because RTF files are text-based like HTML. Throw Distiller into the mix and you've got a web-based, template-driven, maybe even database-driven PDF generator!
Have fun,
Dave
27-Sep-2002 01:29
A Notes example:
$session = new COM "Lotus.NotesSession" );
$session->Initialize($password);
$someDB = "C:\Lotus\Notes\Data\somedb.nsf";
$db = $session->GetDatabase("", $someDB) or die("Cannot get someDB.nsf");
$view = $db->GetView("some_view") or die("Some View not found");
$doc = $view->GetFirstDocument() or die("Unable to get Initial Some Document");
// loop through
while($doc){
$col_vals = $doc->ColumnValues();
echo $col_vals[0];
$doc = $view->GetNextDocument($doc);
}
27-Aug-2002 07:31
When first writing applications instancing COM objects I always faced the problem of the instanced program not terminating correctly although everything else worked fine. In fact the process had to be killed manually by using the task manager. When experimenting a bit I was able to isolate the cause for this peculiar behaviour to be illustrated by the sample code below:
<?php
//Accessing arrays by retrieving elements via function ArrayName(Index) works, but certainly is neither efficient nor good style
$excel=new COM("Excel.Application");
$excel->sheetsinnewworkbook=1;
$excel->Workbooks->Add();
$book=$excel->Workbooks(1);
$sheet=$book->Worksheets(1);
$sheet->Name="Debug-Test";
$book->saveas("C:\\debug.xls");
$book->Close(false);
unset($sheet);
unset($book);
$excel->Workbooks->Close();
$excel->Quit();
unset($excel);
//Accessing arrays as usual (using the [] operator) works, buts leads to the application not being able to terminate by itself
$excel=new COM("Excel.Application");
$excel->sheetsinnewworkbook=1;
$excel->Workbooks->Add();
$excel->Workbooks[1]->Worksheets[1]->Name="Debug-Test";
$excel->Workbooks[1]->saveas("C:\\debug.xls");
$excel->Workbooks[1]->Close(false);
$excel->Workbooks->Close();
$excel->Quit();
unset($excel);
?>
The sample code performs the same action twice and each time the file is properly created. Yet for some mysterious reason the instanced excel process won't terminate once you've accessed an array the way most programmers (especially those who do a lot of oop in c++) do! Therefore until the PHP developers become aware of this problem we'll have to use the inefficient coding style illustrated in the first example.
21-Aug-2002 07:30
This is a sample to make a parametrized query using ADO via COM, this sample was used with Foxpro but will work's with most ADO complient databases. This was tested on IIS with WIN XP pro.
<?
// Create the main connection
$dbc = new COM("ADODB.Connection") or die ("connection create fail");
$dbc->Provider = "MSDASQL";
$dbc->Open("FoxDatabase");
// Creates a temporary record set
$RSet = new COM("ADODB.Recordset");
// Create one ADO command
$cm = new COM("ADODB.Command");
$cm->Activeconnection = $dbc;
// the ? inside values will be the parameters $par01 and $par02
$cm->CommandText = "Insert Into testtable ( mycharfield,mymemofield) VALUES (?,?)" ;
$cm->Prepared = TRUE;
// Creates and append 2 parameters
$par01 = $cm->CreateParameter('ppar01',129,1,50,'ABCDEFGHIKL');
$cm->Parameters->Append($par01);
$par02 = $cm->CreateParameter('ppar01',129,1,50,'123456789012346789');
$cm->Parameters->Append($par02);
// Call 10 times the exec comand to show 10 different queries
for ($i = 1; $i <= 10; $i++) {
$par01->Value = 'Count '.$i;
$par02->Value = 'Passing here'.$i.' times';
$RSet = $cm->Execute;
}
$RSet = $dbc->Execute("select * from testtable");
while (!$RSet->EOF){
echo $RSet->fields["mycharfield"]->value.' ' ;
echo $RSet->fields["mymemofield"]->value ;
echo '<BR>';
$RSet->movenext();
}
$RSet->close;
$dbc->close;
$cm->close;
$RSet = null;
$dbc = null;
$cm = null;
?>
29-Jun-2002 02:48
Complementing Alex's Excell Example, let's print the SpreadSheet to a PDF file using Acrobat Distiller:
$wkb->PrintOut(NULL, NULL, NULL, NULL, "Acrobat Distiller");
There you go!!!
19-Apr-2002 08:34
an easy way to convert your file from .doc to .html
// starting word
$word = new COM("word.application") or die("Unable to instanciate Word");
// if you want see thw World interface the value must be '1' else '0'
$word->Visible = 1;
//doc file location
$word->Documents->Open("E:\\first.doc");
//html file location '8' mean HTML format
$word->Documents[1]->SaveAs("E:\\test_doc.html",8);
//closing word
$word->Quit();
//free the object from the memory
$word->Release();
$word = null;
02-Apr-2002 08:01
An easy way to send e-mail using your default Outlook account:
<?
$objApp = new COM("Outlook.Application");
$myItem = $objApp->CreateItem(olMailItem);
$a=$myItem->Recipients->Add("admin@purplerain.org");
$myItem->Subject="Subject";
$myItem->Body="This is a Body Section now.....!";
$myItem->Display();
$myItem->Send();
?>
08-Mar-2002 05:59
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
28-Feb-2002 02:11
now in PHP >=4.0.6
programming in window can use the
ADO through the COM like this:
$dbconn=new COM ("ADODB.Connection") or die ("connection create fail");
$dbconn->Open("Provider=sqloledb;Data Source=ndht;Initial Catalog=printers;User Id=printers;Password=printers;");
$rec=new COM("ADODB.Recordset") or die ("create Recordset error");
while (!$rec->EOF)
{
echo $rec->fields["fieldname"]->value."<br>";
$rec->movenext();
}
$rec->close();
$dbconn->close();
but there's still a little question of working with the image field of mssql server.
01-Apr-2001 09:37
I thought i'd share with those of you unfamiliar with one of the cool things
about developing php on win32 systems..
http://www.phpbuilder.net/columns/alain20001003.php3
This is a good article, but i don't think the author hit the nail on the
head showing how useful this can be.
Now, checkout this article:
http://www.4guysfromrolla.com/webtech/040300-1.shtml
Notice how he describes 1) how to build a com object & 2) how to call and
use the com object from ASP.
In php, this is how you would call the same object:
<?
$instance = new COM("Checkyear.LeapYear");
$isleapyear = $instance->IsLeapYear($year);
$instance->close();
if($isleapyear) {
echo "The <b>$year</b> is a leap year";
}
else {
echo "The <b>$year</b> is not a leap year";
}
?>
I hope this helps someone.. you can contact me at kevin@vcconcepts.com if
you would like to discuss this further.