10 tips for PHP scripts: Access COM functions

Learn how to access Component Object Model (COM) functions with PHP.

By Julie Meloni

If you're an adventurous soul, and you're running PHP on Windows using the CGI, ISAPI or Apache module version, you can access the COM functions. Now, explaining COM (Microsoft's Component Object Model) is left to Microsoft and very large books. However, for a little taste of what COM can do, here's a common (no pun intended) code snippet.

This code snippet uses PHP to open Microsoft Word in the background, open a new document, type some text, save the document, and close the application:

// create a reference to a new COM component (Word)
$word = new COM("word.application") or die("Can't start Word!");

// print the version of Word that's now in use
echo "Loading Word, v. {$word->Version}<br>";

// set the visibility of the application to 0 (false)
// to open the application in the forefront, use 1 (true)
$word->Visible = 0;

// create a new document in Word

// add text to the new document
$word->Selection->TypeText("Testing 1-2-3...");

//save the document in the Windows temp directory

// close the connection to the COM component

// print another message to the screen
echo "Check for the file...";

Suppose you're running an intranet Web site that has data stored in Microsoft SQL Server, and your users need that data in Excel format. You can have PHP run the necessary SQL queries and format the output, then use COM to open Excel, dump the data stream into it, and save the file on the user's desktop.

Julie Meloni is the technical director at i2i Interactive and is an avowed proponent of Linux and the open source community. A regular contribtor to CNET, she has written a few books on PHP and other technologies.

Editor's Picks

Free Newsletters, In your Inbox