我的应用程序有一个 jar 文件,其中包含多个类。 PHP 通过命令提示符调用该 jar 文件。我使用以下 PHP 代码片段来调用 jar 文件。
<?php
$result=popen('java -jar D:\\Development\\Filehandler\\dist\\Filehandler.jar getConfigLang', "r");
while(!feof($result)){
print fread($result, 1024);
flush();
}
fclose($result);
?>
这里的问题很有趣。我能够获得主函数中的“System.out.println”语句。但无法获取其他类的输出语句。
我也尝试过使用 exec() 。 .jar 工作正常,当直接从命令提示符调用时,它工作正常。
有没有办法捕获整个输出?
最佳答案
您是否尝试过使用 proc_open 来代替:
http://au.php.net/manual/en/function.proc-open.php
它允许您设置管道“将被设置为文件指针的索引数组,该数组对应于所创建的任何管道的 PHP 末尾。”
来自 php.net 的示例
<?php
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("file", "/tmp/error-output.txt", "a") // stderr is a file to write to
);
$cwd = '/tmp';
$env = array('some_option' => 'aeiou');
$process = proc_open('php', $descriptorspec, $pipes, $cwd, $env);
if (is_resource($process)) {
// $pipes now looks like this:
// 0 => writeable handle connected to child stdin
// 1 => readable handle connected to child stdout
// Any error output will be appended to /tmp/error-output.txt
fwrite($pipes[0], '<?php print_r($_ENV); ?>');
fclose($pipes[0]);
echo stream_get_contents($pipes[1]);
fclose($pipes[1]);
// It is important that you close any pipes before calling
// proc_close in order to avoid a deadlock
$return_value = proc_close($process);
echo "command returned $return_value\n";
}
?>
关于java - 通过 cmd 提示符从 PHP 执行 .jar 文件并捕获输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3261994/