11

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!

4
  • 6
    This might be what you are looking for. Commented Oct 15, 2012 at 13:55
  • 1
    @NickolayRatchev or Edmund, one of you should go ahead and write up an answer for this since you both seem t ohave figured it out. Commented Oct 15, 2012 at 20:36
  • 1
    @Edmund: You should post that as an answer, not as a comment. I went ahead and removed the "Update" section of your question, since it is in fact an answer to your own question Commented Oct 15, 2012 at 20:40
  • A more complete solution based on the answer below: stackoverflow.com/q/40960138/243233 Commented Dec 4, 2016 at 15:37

1 Answer 1

7

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
}
Sign up to request clarification or add additional context in comments.

7 Comments

The three imports: import php.java.bridge.*; import php.java.script.*; import php.java.servlet.*; are useless, no?
No, the ScriptEngine needs the three imports in order to run the PHP.
Gives a php not found error. Help?
How to read the output of php code (say if it returns of echos something)?
@EdmundGentle I don't want to start a new question since so many have been marked as duplicates but is this still possible? I've looked for about an hour now and I can't find php-script.jar anywhere on the internet. Is it s till required? Thanks.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.