Possible Duplicate:
Calling PHP from Java
I was wondering how I could run PHP code within Java. Using the ScriptEngine, I am able to run JavaScript:
String code="print(5+5);"; //sample bit of code
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByExtension("js");
try {
engine.eval(code);
} catch (ScriptException ex) {
//catch statement
}
To run this, I imported the library javax.script.*
. I believe to run PHP I would have to import a similar library, and change the third line of the code above to the extension php
. Unfortunately, I don't know which library this is. I have Googled to try and find the answer, and came across the PHP/Java Bridge library but I don't think this is exactly what I'm looking for, as it is focussed on running Java through PHP (as far as I know).
I hope I haven't missed anything out, and any help would be greatly appreciated!
There are two possible ways to bridge PHP and Java: you can either integrate PHP into a Java Servlet environment, which is the more stable and efficient solution, or integrate Java support into PHP. The former is provided by a SAPI module that interfaces with the Servlet server, the latter by this Java extension.
It is possible to insert the content of one PHP file into another PHP file (before the server executes it), with the include or require statement. The include and require statements are identical, except upon failure: require will produce a fatal error (E_COMPILE_ERROR) and stop the script.
Executing PHP files ¶ There are three different ways of supplying the CLI SAPI with PHP code to be executed: Tell PHP to execute a certain file. Both ways (whether using the -f switch or not) execute the file my_script.
The solution to this problem is to download the files JavaBridge.jar
, php-script.jar
and php-servlet.jar
from http://php-java-bridge.sourceforge.net/pjb/download.php then import them into your class:
import javax.script.*;
import php.java.bridge.*;
import php.java.script.*;
import php.java.servlet.*;
Then the code can then be run as before:
String code="echo 5+5;"; //sample bit of code
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByExtension("php");
try {
engine.eval(code);
} catch (ScriptException ex) {
//catch statement
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With