Joey.Z
Joey.Z

Reputation: 4750

Execute java class in PHP

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.

I have add the class file to my CLASSPATH. And I can execute the command in cmd correctly as follows:

enter image description here

In my PHP file I call this program by

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).

Upvotes: 1

Views: 12558

Answers (4)

Footniko
Footniko

Reputation: 2752

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.

Upvotes: 1

starshine531
starshine531

Reputation: 591

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.

Also, I recommend using the following link to download it. (it's the same one as the link in downloads->documentation)

http://sourceforge.net/projects/php-java-bridge/files/Binary%20package/php-java-bridge_6.2.1/php-java-bridge_6.2.1_documentation.zip/download

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.

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.

Upvotes: 2

Peng Qi
Peng Qi

Reputation: 1462

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");
}

Upvotes: 0

oentoro
oentoro

Reputation: 750

Well, it yields array right? so instead print_r($output) try print($output[0]), that outputting 'Hello World' on my console :D

Upvotes: 0

Related Questions