在 PHP 中执行 java 类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15860236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Execute java class in PHP
提问by zoujyjs
I want to call a java program and fetch it's output in stdout. I followed the suggestions in stackoverflow. But it doesn't work.
我想调用一个java程序并在stdout中获取它的输出。我遵循了stackoverflow 中的建议 。但它不起作用。
I have add the class file to my CLASSPATH. And I can execute the command in cmd correctly as follows:
我已将类文件添加到我的 CLASSPATH。我可以正确执行cmd中的命令如下:
In my PHP file I call this program by
在我的 PHP 文件中,我通过
exec("java Hello", $output);
print_r($output);
It yields nothing but:
它只产生:
Array()
What is the problem? How can I fix this?
问题是什么?我怎样才能解决这个问题?
ps: Hello is a demo program, actually the program I want to call is much more complicated which might take 2 or more seconds in my machine(i5 4G).
ps:你好是一个演示程序,实际上我要调用的程序要复杂得多,在我的机器(i5 4G)中可能需要2秒或更长时间。
回答by starshine531
I would recommend using Java/PHP Bridge found here: http://php-java-bridge.sourceforge.net/pjb/It's quite easy to install and works very well.
我建议使用此处找到的 Java/PHP Bridge:http: //php-java-bridge.sourceforge.net/pjb/它很容易安装并且运行良好。
Also, I recommend using the following link to download it. (it's the same one as the link in downloads->documentation)
另外,我建议使用以下链接下载它。(与下载->文档中的链接相同)
The file is JavaBridge.war. You'll probably want to use Tomcat for the Java EE container. Once Tomcat is set up, you just put this file in the webapps folder and it's installed.
该文件是 JavaBridge.war。您可能希望将 Tomcat 用于 Java EE 容器。Tomcat 设置好后,您只需将此文件放在 webapps 文件夹中即可安装。
If you want to regularly use java classes in PHP this is the best method I know of and I have tried a lot of them. Resin also worked, but it didn't play nice with my mail server.
如果你想经常在 PHP 中使用 java 类,这是我所知道的最好的方法,我已经尝试了很多。Resin 也能用,但它在我的邮件服务器上效果不佳。
回答by Footniko
Try this:
试试这个:
exec('java -cp .:/path/to/folder/of/your/file Hello 2>&1', $output);
print_r($output);
the 2>&1
need to display errors.
在2>&1
需要显示错误。
回答by oentoro
Well, it yields array right? so instead print_r($output)
try print($output[0])
, that outputting 'Hello World' on my console :D
好吧,它产生数组对吗?所以改为print_r($output)
尝试print($output[0])
,在我的控制台上输出“Hello World”:D
回答by Peng Qi
try pipe
试管
$command = 'java Hello';
$descriptorspec = array(
1 => array(
'pipe', 'w'
)
);
$process = proc_open($command, $descriptorspec, $pipes);
if (!is_resource($process)) {
exit("failed to create process");
}
$content = stream_get_contents($pipes[1]);
fclose($pipes[1]);
if (proc_close($process) === 0) {
print_r($content);
}else{
exit("failed to execute Hello");
}