2

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)

Calling PHP from Java (closed)

How can I run PHP code within a Java application? (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? To give more context, someone has given me a PHP file containing code for some method foo that returns a string. How do we invoke this from 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.

The answer below explains how to do this using the PHP/Java bridge.

The answer is in Scala but would be easy to read for Java programmers.

1 Answer 1

2

Code created from this SO answer and this example:

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. Then create a file php.scala with the above code. Then run:

scalac php.scala

and

scala javaphp.Test
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.