简体   繁体   English

从 Java (Scala) 调用 PHP 代码并获得结果

[英]Invoke PHP code from Java (Scala) and get result

This seems to have been asked in several places and has been marked as "closed" and "off-topic".这似乎在几个地方被问过,并被标记为“关闭”和“离题”。 However, people seem to have this problem constantly然而,人们似乎经常遇到这个问题

invoking a php method from java (closed) 从java调用php方法(关闭)

Calling PHP from Java (closed) 从 Java 调用 PHP (已关闭)

How can I run PHP code within a Java application? 如何在 Java 应用程序中运行 PHP 代码? (closed) (关闭)

This answer in the last question partly answers this but does not clarify how to read the outputs.最后一个问题中的这个答案部分回答了这个问题,但没有说明如何读取输出。

I finally found the answer to the question:我终于找到了问题的答案:

How do I run a PHP program from within Java and obtain its output ?如何从 Java 中运行 PHP 程序并获取其输出 To give more context, someone has given me a PHP file containing code for some method foo that returns a string.为了提供更多上下文,有人给了我一个 PHP 文件,其中包含一些返回字符串的方法foo代码。 How do we invoke this from JVM?我们如何从 JVM 调用它?

Searching on Google is not helpful as all articles I found don't explain how to call PHP from Java but rather Java from PHP.在 Google 上搜索并没有帮助,因为我发现的所有文章都没有解释如何从 Java 调用 PHP,而是从 PHP 调用 Java。

The answer below explains how to do this using the PHP/Java bridge.下面的答案解释了如何使用 PHP/Java 桥来做到这一点。

The answer is in Scala but would be easy to read for Java programmers.答案是在 Scala 中,但对于 Java 程序员来说很容易阅读。

Code created from this SO answer and this example :这个 SO 答案这个例子创建的代码:

package javaphp

import javax.script.ScriptEngineManager
import php.java.bridge._
import php.java.script._
import php.java.servlet._

object JVM{ // shared object for PHP/JVM communication
  var out = ""
  def put(s:String) = {
    out = s
  }
}

object Test extends App {
  val engine = (new ScriptEngineManager).getEngineByExtension("php")  
  val oldCode = """
    <?php
        function foo() {
            return 'hello';
            // some code that returns string
        }
    ?>
  """
  val newCode = """
    <?php
        $ans = foo();
        java('javaphp.JVM')->put($ans);
    ?>
  """+oldCode

  // below evaluates and returns
  JVM.out = "" //reset shared output
  engine.eval(newCode)
  println("output is : "+JVM.out) // prints hello
}

To run this file:要运行此文件:

Install PHP, Scala and set path correctly.安装 PHP、Scala 并正确设置路径。 Then create a file php.scala with the above code.然后用上面的代码创建一个文件php.scala Then run:然后运行:

scalac php.scala

and

scala javaphp.Test

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM