0

This is the scenario: I have a php script that builds html and echoes it to the browser. Just before html is echoed, I need to call executable java jar file and pass it the html so it could process it and return it back to php to be echoed out.

The only way I can come up with now is save html to temporary file, pass java the file name, let it modify it and load it again in php. I'm guessing this can be quite slow and requires file being written to disk, then read, modified, written again and read again.

My question is this: in given scenario is there a faster way of passing java the html file and returning it to php?

My current stack: Apache 2.4, PHP 5.4.7, Java 7, OS: Ubuntu

4

1 回答 1

1

I've used Marc B suggested solution and since there is no clear example of this particular situation online, I'm pasting my php and java code in case someone needs it in the future:

PHP code:

<?php

$process_cmd = "java -jar test.jar";

$env = NULL;
$options = ['bypass_shell' => true];
$cwd = NULL;
$descriptorspec = [
    0 => ["pipe", "r"], // stdin is a pipe that the child will read from
    1 => ["pipe", "w"], // stdout is a pipe that the child will write to
    2 => ["pipe", "w"]  // stderr is a file to write to
];

$process = proc_open($process_cmd, $descriptorspec, $pipes, $cwd, $env, $options);

if (is_resource($process)) {

    //feeding text to java
    fwrite($pipes[0], "Test text");
    fclose($pipes[0]);

    //echoing returned text from java
    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 "\n command returned $return_value\n";
}

?>

JAVA code:

package Test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test {

    public static void main(String[] args) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String input;

        while ((input = br.readLine()) != null) {
            System.out.println(input + " java test string ");
        }

    }

}
于 2013-07-26T09:22:43.253 回答