无法使用PHP将lscript的输出捕获到文件中


Not able to capture the ouput of lscript into the file using PHP

我想使用PHP将TCL脚本的输出捕获到文件中。我能够将hello world输出捕获到文件,但是当我运行长脚本时,这需要时间并且输出很大,那么我就没有。

下面是我的代码:
 <?php
 ob_start();
 passthru(' /path/to/file/helloworld ');
 $out1 = ob_get_contents();
 ob_end_clean();
 $fp = fopen('/path/to/file/output.txt',w);
 fwrite($fp,$out1);
 fclose($fp);
 echo'<pre>', $out1,'</pre>';
 #var_dump($out1);
 ?>

请告诉我长TCl脚本有什么问题

编辑:对于长时间运行的脚本(如守护进程),我建议使用popen并从资源中流式传输内容。

的例子:

<?php
$h = popen('./test.sh', 'r');                                                                                                                                                        
while (($read = fread($h, 2096)) ) {                                                                                                                                                 
    echo $read;
    sleep(1);                                                                                                                                                                        
}
pclose($h);

你应该检查你的php.ini的"max_execution_time"。如果你是在一个web服务器上下文中也检查配置的超时。

编辑结束

你试过吗?

第二个参数是对一个数组的引用,该数组被脚本输出

填充。简而言之:

<?php
$output = array();
exec('/path/to/file/helloworld', $output);
file_put_contents('/path/to/file/output.txt', implode("'n", $output));

的例子:

test.sh:

#!/bin/bash                                                                                                                                                                          
echo -e "foo'nbar'nbaz";                                                                                                                                                             
echo -e "1'n2'n3"; 

test.php:

<?php
$output = array();
exec('./test.sh', $output);
var_dump($output); 
输出:

php test.php
array(6) {
  [0]=>
  string(3) "foo"
  [1]=>
  string(3) "bar"
  [2]=>
  string(3) "baz"
  [3]=>
  string(1) "1"
  [4]=>
  string(1) "2"
  [5]=>
  string(1) "3"
}

引用php官方文档(链接见上面)

如果存在output参数,则指定的数组将用命令的每一行输出填充