Connecting to WMI with PHP - Spit it Out
(Page 4 of 5 )
Now, here’s something that’s interesting to know -- you can’t use the exec function to work with WMI, it won’t output. Instead you have to use the passthru function. This is because the passthru function runs the program and returns the raw output. Exec doesn’t do that, however you can use passthru in the exact same way you use exec so you don’t really need to worry about anything. To simply send your information to the browser all you’ll have to do is this.
echo passthru('wmic cpu get loadpercentage /format:newxml');
That’s it, no big deal, right!? Well, no, that’s not really it. That will work if you want to look at the source of the page every time to see the data, which I don’t think you’d want to do -- you’ll have to make it parse the data with an XML parser or simpleXML. I prefer simpleXML because it’s, well, simple. So I came up with the small little function:
function parse_stat($instance){
ob_start();
passthru('wmic '.$instance.' /format:newxml');
$results=ob_get_clean();
$xml[] = simplexml_load_string($results)
Return $xml;
}
This will return an array of all my WMI data which I can then put in a foreach loop and echo out, where I want it. This function is also fairly nice because you only have to tell it the WQL string, no formatting data. This is how it’s used.
parse_stat("os get FreePhysicalMemory,TotalVirtualMemorySize,FreeVirtualMemory,
TotalVisibleMemorySize");
parse_stat("cpu get loadpercentage");
parse_stat("logicaldisk where drivetype=3 get size,name,freespace");
foreach ($xml as $wmi){
echo $wmi->property.”: “.$wmi->value;
}
And that is just about all you need to know to get started working with WMI from PHP.
Next: Just a Few More Words >>
More Windows Scripting Articles
More By James Murray