Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
PHP Function for parsing vmstat output
<?php
// TEST
// $res[] = "procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----";
// $res[] = " r b swpd free buff cache si so bi bo in cs us sy id wa";
// $res[] = " 0 0 0 10376 148188 291056 0 0 4 29 85 9 1 0 98 1";
// // or
// // exec('vmstat', $res);
// print_r(parseVMStatOutput($res));
function parseVMStatOutput($lines) {
$titles = explode(' ', $lines[0]);
foreach ($titles as $n => $_t) {
$titles[$n] = array(
'name'=>trim($_t, '-'),
'len'=>strlen($_t)
);
}
$subtitleLine = $lines[1];
foreach ($titles as $n => $_t) {
$subtitles = substr($subtitleLine, 0, $_t['len']);
$subtitleLine = substr($subtitleLine, $_t['len']+1);
preg_match_all('/(?:[ \t]*([0-9a-zA-Z]+))/', $subtitles, $subtitleMatch);
$titles[$n]['subtitles'] = $subtitleMatch[1];
}
$results = array();
for ($i = 2; $i<count($lines); $i++) {
preg_match_all('/(?:[ \t]*([0-9a-zA-Z]+))/', $lines[$i], $valuesMatch);
$values = $valuesMatch[1];
$_line = array();
$j = 0;
foreach ($titles as $_t) {
foreach ($_t['subtitles'] as $_s) {
$_line[$_t['name']][$_s] = $values[$j++];
}
}
$results[] = $_line;
}
return count($results)==1 ? $results[0] : $results;
}

mishanon commented Sep 8, 2014

poor function
i catch only 9 parameters from 19

Array
(
[procs] => Array
(
[r] => 0
[b] => 0
[w] => 0
)

[memory] => Array
    (
        [vm] => 4866940
    )

[page] => Array
    (
        [flt] => 1355908
    )

[disks] => Array
    (
        [r] => 545
        [da0] => 0
    )

[faults] => Array
    (
        [in] => 0
    )

[cpu] => Array
    (
        [us] => 0
    )

)

and if u using regex, it is poor performance

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment