2014-06-18 48 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

我认为这并不是他所需要的:虽然它非常紧凑,但使用此方法,您完全无法控制要保存的文件。此外,如果他想在保存之前处理输出... –

相关问题