执行linux命令并将输出存储在php数组中

时间:2013-05-18 16:16:03

标签: php linux command-line

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

我试试这个,

    // 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变量的结果,如果有更好的方法呢?

1 个答案:

答案 0 :(得分: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将根据使用的函数评估数据类型。

相关问题