2014-06-18 42 views
0

我會提供一個例子 我想要的目錄列表寫入到文件 所以我這樣做如何編寫exec命令(在PHP中)輸出到文件?

<?php 
$command="dir"; 
exec($command,$output); 
//i want the directory list to be written to a file 
// so i did this 
$fp=fopen("file.txt","w"); 
fwrite($fp, $output); 
//its actually writing the 0(return value for exec is int) to the file 
// but i want the list of directories to be written to file 
?> 

其實際寫入0(回報EXEC值INT),該文件 但我想要目錄列表寫入文件 請告訴我一種方法來做到這一點

回答

0

您可以簡單地使用shell_exec

<?php 
    $output = shell_exec('dir'); 

    $fp=fopen("file.txt","w"); 
    fwrite($fp, $output); 
?> 
+0

謝謝@AlexGidan。有用。 :) – user3737132

+0

不客氣,很高興它幫助! –

0

我認爲你的針你應該使用命令「passthru」。

下面的例子:

<?php 
    $command = exec('dir', $outpout); 
    $data = ""; 
    foreach($output AS $key=>$val){ 
     $data .= $val . "\n"; 
    } 

    $fp = fopen('file.txt', 'w') or die("i cant write...permission ?"); 
    fwrite($fp, $data); 
    fclose($fp); 
?> 

讓我知道,如果它

有一個愉快的一天

安東尼

附:感謝凱文

+0

錯誤。 passthru直接顯示輸出並返回void。 –

+0

哦......正確......感謝Kevin –

0

您可以在exec調用直接做到這一點(這是短):

exec("dir > file.txt") 

無論如何,你的代碼是錯誤的,因爲$輸出是一個數組。 固定碼:

$command="dir"; 
exec($command,$output); 
$fp=fopen("file.txt","w"); 
fwrite($fp, join("\n",$output)) 

和較短代碼:

exec("dir",$output); 
file_get_contents("file.txt",join("\n",$output)); 
+0

我認爲這並不是他所需要的:雖然它非常緊湊,但使用此方法,您完全無法控制要保存的文件。此外,如果他想在保存之前處理輸出... –

相關問題