Use java code in php

Embedding Java in PHP [duplicate]

For a time now, I’ve been searching on how to embed java in php but found questions that give possible solutions and others that say it’s impossible. I happen to have some java code working and I need it working in a php application, I tried making the same exact code in php language (of course, in php) but it doesn’t work, so, what I want to know is: How can I run my java functions using php? Thank you all.

«I tried making the same exact code in php but it doesn’t work» -Well, if it was the same exact code then that’s not really surprising, since PHP can’t interpret Java code. If implementing the functionality in PHP isn’t an option (though it really should be) then perhaps you could package the Java code into an application or some sort of standalone service that the PHP code would call? From within the PHP code’s domain it should make no difference, it’s just calling a dependency regardless of how or where that dependency is implemented.

PHP can’t call it directly (at least not without some kind of intermediary tool, and I don’t know of any). You’re probably better off setting up the Java code into an application context of its own (a web service, a local application, etc.) and then just have PHP call that application (a web service call, running a command-line application and checking its output, etc.). (Again, this is if the Java code’s logic can’t simply be re-implemented in PHP, which I suspect it can. That would really be best.)

Источник

Run Java program inside PHP code [duplicate]

I am trying to make a simple recommender system, and I found that with mahout it is pretty easy to make one. I have the following code (I am running it on eclipse and everything works great:

package com.predictionmarketing.RecommenderApp; import java.io.File; import java.io.IOException; import org.apache.mahout.cf.taste.common.TasteException; import org.apache.mahout.cf.taste.impl.model.file.FileDataModel; import org.apache.mahout.cf.taste.impl.neighborhood.ThresholdUserNeighborhood; import org.apache.mahout.cf.taste.impl.recommender.GenericUserBasedRecommender; import org.apache.mahout.cf.taste.impl.similarity.PearsonCorrelationSimilarity; import org.apache.mahout.cf.taste.model.DataModel; import org.apache.mahout.cf.taste.neighborhood.UserNeighborhood; import org.apache.mahout.cf.taste.recommender.RecommendedItem; import org.apache.mahout.cf.taste.recommender.UserBasedRecommender; import org.apache.mahout.cf.taste.similarity.UserSimilarity; /** * Java's application, user based recommender system * */ public class App < public static void main( String[] args ) < // Modelo DataModel model = null; // Inicializar similaridad UserSimilarity similarity = null; // Leer .cv userID, itemID, value try < model = new FileDataModel(new File("data/dataset.csv")); >catch (IOException e1) < // TODO Auto-generated catch block e1.printStackTrace(); >// Encontrar matriz de similaridad try < similarity = new PearsonCorrelationSimilarity(model); >catch (TasteException e) < // TODO Auto-generated catch block e.printStackTrace(); >UserNeighborhood neighborhood = new ThresholdUserNeighborhood(0.1, similarity, model); UserBasedRecommender recommender = new GenericUserBasedRecommender(model, neighborhood, similarity); java.util.List recommendations = null; try < recommendations = recommender.recommend(2, 3); >catch (TasteException e) < // TODO Auto-generated catch block e.printStackTrace(); >// Mostrar Recomendaciones for (RecommendedItem recommendation : recommendations) < System.out.println(recommendation.getItemID()); >> > 

However, I need to run this code online because I am making the application on PHP and that is where my problem arises. Is there a way to run this code on PHP, so I can use the «recommendation» variable?

Читайте также:  Css flex row margin

Источник

How to use Java in PHP? [closed]

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

I want to use WordPress for my web development, which is PHP written, including the database connection to MySql. The whole thing is PHP. But I need to use Java to back-end data processing and a number of existing Java open source libraries. A google search shows that PHP/Java Bridge is a way to go. Is that bridge best way to go? If everything is PHP with WordPress, is still a way to use J2EE technologies, inlcuding JSP, Servelet, etc? edit Java is needed becaue I need to run machine learning algorithms, libraries for which are only available for Java. Also, PHP may run into efficiency issues when it’s used to process large amount of data. A good example of libraries in Java I am going to use is those processing Big Data, which are mainly Java, like Hadoop.

It’s not impossible. You need to use a common protocol and pass messages between processes. I’d consider setting up some REST service. You can construct your own protocol using TCP, but I’d advise against it as your setting yourself up for a lot of work and potential bugs.

Ok, now you shed some light in the question. You need to use machine-learning libraries that are already written in Java and it’s a tedious work to move them to PHP (yes, that’s a restriction and a motivation that should be posted in your question body). By knowing this, readers could provide better guidance in the solution of your problem (not me, I don’t know much about this Java bridge).

Please don’t use the comments section for a debate. If you have opinions on PHP vs Java popularity, tweet or blog about it. Getting back to the actual question, @martin can you please edit your question and add all the relevant information to back up why you need to need to mix PHP and Java? Needing machine learning libraries is a decent step in the right direction, but do those libraries need to do something «on their own» based on user data, or are they essential to forming correct page relies; which libraries (have you tried finding PHP equivs); etc.

Читайте также:  Hiding html elements with javascript

1 Answer 1

The very simple answer here is don’t

PHP is designed to, at every page request start up, execute a small series of scripts as a single operation, output the data associated with those scripts and then immediately die after generating the output. It literally does not have time to wait for your Java programs and libraries to do their thing, so don’t try to put one in the other, which is why PHP scripts that rely on databases tend to have heavily optimised databases for immediate retrieval, instead of general databases that rely on joins and selects that take a few seconds to form the correct data response. Neither PHP or users browsing websites have time for that.

What you could do is wrap your java tools in Java Servlets and have them running on the same server/host that your PHP instance is running from, so that your scripts can access the Servlets as http://127.0.0.1:7254/. as it would any other restful API it needs to use while generating your script output, as long as you make damn sure that you’re not going to make PHP wait: if it has to send data to your tools, that is a post-and-forget operation, PHP should not be getting any response back other than an immediate «data accepted» or «data rejected» before the data is then actually handled by your tools. If you need to post data and then get a result back, you’re going to have to use two calls. One to post the data, and then a second call to request the result of that posting.

  • web page generation chain: WordPress CMS based on PHP -> your database
  • web input for processing: WordPress CMS based on PHP -> Java Servlets for machine learning
  • data processing chain: Java Servlets for machine learning -> your database

So you build pages only based on what’s in your data base, you post data to your java Servlets only to get them to start doing something and you don’t wait for a response, their result will end up in your database and you’ll get it for pages once it’s in, and your java programs do what they need to do independently of your WordPress setup.

And if you’re going to do that, you should probably write that functionality as a WordPress plugin that can talk to your Java Servlets.

And now you have a second project you need to work on: turning your java programs into web servers. Not terribly complex, but definitely something you’re going to lose some time on doing right (because you’ll need to wrap with servlets, as well as make sure you can have those running without crashing on the same server as your wordpress instance, which is always fun)

Читайте также:  Float или double java

Источник

Execute java class in PHP

enter image description here

I want to call a java program and fetch it’s output in stdout. I followed the suggestions in stackoverflow. But it doesn’t work. I have add the class file to my CLASSPATH. And I can execute the command in cmd correctly as follows: In my PHP file I call this program by

exec("java Hello", $output); print_r($output); 

What is the problem? How can I fix this? ps: Hello is a demo program, actually the program I want to call is much more complicated which might take 2 or more seconds in my machine(i5 4G).

Try and see what passthru() gives back (instead of exec() ). exec() might be selective sometimes to catch only returned values rather than printed content. Use escapeshellarg() to secure your script against hacks.

If the main() function in your JAVA program returns 1 (return 0 = no errors, 1 = somethings wrong ;)) it means there was an error. It might have something to do that PHP’s commandline doesn’t fetch your JAVA the same way as you do in cmd . Both are of course different settings-wise. Like cakil answered it might work to loop on the Array() you got back, as echo/print in PHP won’t show the inners of an Array by default, like you might be used to in other languages.

@Allendar thanks, I checked the returned Array carefully to ensure that I didn’t miss anything, but it IS empty. And passthru actually gives nothing intead of 1 , I said 1 because I mistakenly set the class. Anyway, thank you. And if this won’t work anyway, I can alternatively try to wrap this in jsp file or some other server-script language. I just want to make it on-line such that users can access the processed data yield by the java program. The worst case is that I have to translate the java program to PHP or other server-script language.

Try to just put return 0; in your JAVA class, at least to test if passthru() is not always giving back 1. It should read RAW-input, so it’s really something with calling JAVA from the PHP script. Maybe (to test) try execute JAVA from it’s absolute path too. The more you test, the more you will mostly get to know 🙂

Источник

Оцените статью