格式化exec()system()输出

时间:2011-10-15 12:55:52

标签: php unix formatting

我需要以表格格式在网页上的unix上获取命令的输出。 这就是我以前做的事情: 这基本上生成了一个html代码,我将其重定向到html页面并从网页访问它。

echo "<html lang=en xml:lang=en xmlns=http://www.w3.org/1999/xhtml>"
echo "<head>"
echo "<title> Team Page </title>"
echo "</head>"
echo "<body bgcolor=#ddfedg font-family=Comic Sans MS>"
echo "<table border=1>"
cat $i|grep %|grep -v on|awk '{printf "<tr><td>%-10s</td> <td>%-10s</td> 
</tr>\n",$NF,$(NF-1)}'
echo "</table>
</body>
</html>"

以前,我曾经在unix上将其设置为cronjob,并且每15分钟生成一个html页面。

现在,我希望实时访问..每次加载页面时都会加载新数据。 我尝试在php中使用exec()和system()函数,但我无法弄清楚如何将输出制表。

输出显示为:

Array ( 
  [0] => / 5% 
  [1] => /stand 10% 
  [2] => /var 36%
  [3] => /usr 40%
  [4] => /ts_undo 31%
  [5] => /ts_temp 96%
  [6] => /ts_redo3 13%
  [7] => /ts_redo2 13%
  [8] => /ts_redo1 13%
  [9] => /ts_index 7%
  [10] => /ts_data 96%
  [11] => /tmp 54%
  [12] => /test_db 65% 
  [13] => /oracle 22%
  [14] => /oraarch 36%
  [15] => /opt 20%
  [16] => /home 38%
  [17] => /Oracle10g 76%
) 

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:1)

// Print out the HTML head
echo "<html lang=\"en\" xml:lang=\"en\" xmlns=\"http://www.w3.org/1999/xhtml\">

  <head>
    <title> Team Page </title>
  </head>

  <body bgcolor=\"#ddfedg\" font-family=\"Comic Sans MS\">
    <table border=\"1\">\n";

// Execute the command to get the data
$cmd = 'bdf|grep %|grep -v on|awk \'{printf "%-10s %-10s\n",$NF,$(NF-1)}\'';
exec($cmd,$output);

// Loop the data
foreach ($output as $line) {
  // Split the row into mount name and usage value
  list($mount,$usage) = preg_split("/\s+/", $line, PREG_SPLIT_NO_EMPTY);
  // Print a table row
  echo "          <tr>\n            <td>$mount</td>\n            <td>$usage</td>\n          </tr>\n";
}

/*

 Assuming the output of 'bdf' is the same as 'df' you could just parse
 the entire output using PHP, and get more information, like this:

 exec('df',$output);
 array_shift($output); // Get rid of column headers
 foreach ($output as $line) { // Loop the remaining data
   if (count($line = preg_split("/\s+/", $line, PREG_SPLIT_NO_EMPTY)) <= 1) continue; // Skip emtpy lines
   echo "          <tr>\n"; // Start an new row
   foreach ($line as $col) echo "            <td>$col</td>\n"; // Print all the columns
   echo "          </tr>\n"; // End the row
 }

*/

// Print the end of the HTML
echo "        </table>\n      </body>\n\n    </html>";

正如您所看到的,它与bash方法不同,我们只是循环数据将其转换为表格。