如何在 Java 应用程序中运行 PHP 代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12897070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I run PHP code within a Java application?
提问by Edmund Gentle
Possible Duplicate:
Calling PHP from Java
可能的重复:
从 Java 调用 PHP
I was wondering how I could run PHP code within Java. Using the ScriptEngine, I am able to run JavaScript:
我想知道如何在 Java 中运行 PHP 代码。使用 ScriptEngine,我可以运行 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).
为了运行它,我导入了库javax.script.*
. 我相信要运行 PHP,我必须导入一个类似的库,并将上面代码的第三行更改为扩展名php
. 不幸的是,我不知道这是哪个图书馆。我用谷歌搜索试图找到答案,并遇到了 PHP/Java Bridge 库,但我不认为这正是我正在寻找的,因为它专注于通过 PHP 运行 Java(据我所知)。
I hope I haven't missed anything out, and any help would be greatly appreciated!
我希望我没有错过任何东西,任何帮助将不胜感激!
采纳答案by Edmund Gentle
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.phpthen import them into your class:
此问题的解决方案是下载文件JavaBridge.jar
,php-script.jar
然后php-servlet.jar
从http://php-java-bridge.sourceforge.net/pjb/download.php将它们导入您的类:
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
}