Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run PHP code within a Java application? [duplicate]

Tags:

java

php

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!

like image 253
Edmund Gentle Avatar asked Oct 15 '12 13:10

Edmund Gentle


People also ask

Can I use PHP code in Java?

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.

How do I run one PHP file from another?

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.

How many ways in which PHP scripts can be executed which?

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.


1 Answers

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
}
like image 178
Edmund Gentle Avatar answered Oct 12 '22 11:10

Edmund Gentle