I would to use sscanf()
or (preferably) fscanf()
to scan /proc/meminfo
and return MemTotal
:
MemTotal: 1027156 kB
MemFree: 774596 kB
Buffers: 23816 kB
Cached: 198300 kB
Since the number of spaces between MemTotal:
and the actual number varies, I'm wondering if sscanf()
is smart enough to parse something like:
sscanf($line, "MemTotal:\s+%d");
Will the padding and alignment specifiers of sprintf()
work with sscanf()
as well?
I would try this out on my own, but I don't have a dev / Linux environment available ATM.
Yes, sscanf
is smart enough to parse that with an arbitrary number of spaces between. You don't even need to specify it in any special way. Just do
sscanf($line, '%s%d');
and you'll get
Array
(
[0] => MemTotal:
[1] => 1027156
)
Unfortunately, the PHP Manual isn't too complete about what you can use as the format string, but since it's based on the UNIX command, you can look at other documentations to find what options you have:
It's a bit fiddly to get them working though.
You're overcomplicating the problem. I'd recommend this approach for converting /proc/meminfo
in a future-proof associative array:
$input = file_get_contents('/proc/meminfo');
$data = [];
$hits = preg_match_all('/^(.*):\s+([0-9]+)/m', $input, $matches);
for($i = 0; $i != $hits; $i++)
$data[$matches[1][$i]] = $matches[2][$i];
var_dump($data);
array(45) {
["MemTotal"]=>
string(6) "508856"
["MemFree"]=>
string(5) "33984"
["Buffers"]=>
string(6) "189124"
["Cached"]=>
string(6) "207512"
...etc...