2013-05-18 96 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非常靈活,您將會對可能性感到驚訝 –