2013-05-18 97 views
0

我正在制作一个用于监视Linux服务器的php网站,因此我使用了linux命令来获取内存使用情况,如(免费)&(cat/proc/meminfo),用于磁盘存储,网络,用户等...我可以执行Linux命令,如exec和shell_exec和back-tick等php命令......但如何将输出存储在php数组中?以及如何将数组中的每个元素移动到字符串或int变量以对其执行一些字符串或int函数?执行linux命令并将输出存储在php数组中

我试试这个,

// get memort details into array !!! 
    $last_line = exec('cat /proc/meminfo', $retval); 
    // this will return just the memory total 
    echo $retval[1]; 
    echo "<br> <br>"; 
    // this will move the memory total into variable 
    $memory_total=$retval[0]; 
    echo "<br> <br> the memory total by variable is $memory_total <br><br> "; 

    implode($memory_total); 

    //this will give me the memory total in KB 
    echo substr($memory_total,9); 
    echo "<br> <br>"; 

,但我想要得到的结果在int变量,如果有应该是一个更好的办法?

+0

我不明白这个问题。 '$ retval'是一个PHP数组。 – Barmar

+0

'implode($ memory_total)'没有任何意义。语法是'implode($ separator,$ array)'。而且你没有在任何地方分配结果。至于在int变量中获得结果,PHP会在必要时自动将字符串转换为int,但如果需要强制执行,则可以使用显式的'(int)'cast。 – Barmar

回答

0

Regular Expressions会让你的生活变得简单。

<?php 

// Why cat in a shell to get info from one file? use the right/easy function! 
$data = file_get_contents('/proc/meminfo'); 

// PCRE will save you in many cases! 
preg_match_all("/^([^:]+):\s+([0-9]+)\s*([a-z]+)?$/Umi",$data,$meminfo,PREG_SET_ORDER); 

// All you need is here 
var_dump($meminfo); 

您对int和string的问题是谁看不懂的部分about types in PHP page一个常见的错误。我强烈地指出,你阅读了基本章节手册,因为许多关于数据操作的问题都将被回答。 PHP将根据所使用的函数评估数据类型。

+0

谢谢,它的工作原理。但我需要分离值,因为我想用它做图表或表格,我可以用$ meminfo和var_dump来使用它吗? –

+0

您可以通过多种方式使用数组$ meminfo,请阅读更多关于PHP语法以及如何操作数组的信息,PHP非常灵活,您将会对可能性感到惊讶 –