【问题标题】:Write terminal output results to file in php将终端输出结果写入php文件
【发布时间】:2013-01-15 13:41:04
【问题描述】:

我已经使用系统运行了我的命令,我希望它将终端结果复制到一个名为 output.txt 的文件中。当我在浏览器上运行我的 php 脚本时,它会显示结果,但不会在 output.txt 中显示该文件是空的。

echo '<pre>';

$last_line = system('ruby /home/simon/ruby-grok/examples/result.rb', $retval);

echo '</pre>';

$out = fopen('output.txt', 'w'); //output handler
fputs($out,$last_line); //writing output operation
fclose($out); 

【问题讨论】:

    标签: php system output


    【解决方案1】:

    代码看起来不错。 脚本是否有权写入该特定文件?你可以尝试代替

    $out = fopen('output.txt', 'w'); //output handler
    fputs($out,$last_line); //writing output operation
    fclose($out); 
    

    这样说:

    file_put_contents('output.txt',$last_line);
    

    编辑:

    顺便说一句,我忘了问。您的浏览器显示什么输出? $out 变量中有数据吗?

    【讨论】:

    • 在我的浏览器上显示结果。它确实写但它只写结果的最后一行,有没有办法逐行写入
    • 逐行编号.. 但你可以使用 exec($cmd . " > $pathToFile");而不是系统命令 - 这样系统会将整个输出直接写入给定路径上的文件
    • 这不会在浏览器上显示输出。我希望它显示在浏览器上并写入文件中。我应该有另一种方法可以尝试。 exec 似乎不起作用,但在浏览器系统上的显示似乎起作用。
    • 然后使用 shell_exec - 这将返回输出。将返回值放入变量中并将其回显到浏览器并使用 file_put_contents 保存
    【解决方案2】:

    使用反引号会更好。

    $variable = `ls -l`;
    

    然后:

    $out = fopen('output.txt', 'w'); //output handler
    
    fputs($out,$variable); //writing output operation
    
    fclose($out); 
    

    或:

    file_put_content('output.txt',$variable);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-02
      • 1970-01-01
      • 2014-11-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-07
      • 2016-04-11
      相关资源
      最近更新 更多