[英]Problems with output from exec in PHP
您好,我正在尝试在PHP中输出内存使用情况。
我的代码看起来像这样:
exec('free -m', $out);
var_dump($out[1]);
list($mem, $total, $used, $free, $shared, $buffers, $cached) = explode(" ", $out[1]);
echo "Memory: " .$used. "/" . $total;
现在的问题是文本打印
Memory: /
var_bump给了我这个:
string(73) "Mem: 3024 1968 1055 0 159 608"
此字符串不应为(73),而应为(29)。 如果我创建自己的数组,则完全没有问题:
$out = array('','Mem: 3024 2020 1003 0 121 708','');
string(29) "Mem: 3024 1968 1055 0 159 608"
谁能给我解决方案或调试此产品的下一步?
最好的问候,艾伦
当我运行free -m
,我实际上得到了大约73个字符(其中有很多空格):
Mem: 2047 0 2047 0 0 0
我想你会发现这是造成你的空used
和total
: explode
在Mem:
和2047
之间的那些空间的某处拾取空字符串。
一种解决方案是将preg_split
与"/\\s+/"
分隔符一起使用。
删除空格,例如:
explode(" ", preg_replace('/\s+/', ' ', $out[1]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.