设为首页 收藏本站
查看: 279|回复: 0

[经验分享] PHP & Java

[复制链接]

尚未签到

发表于 2017-3-3 09:44:03 | 显示全部楼层 |阅读模式
  The Java extension is an extremely exciting tool. By learning how to use this module, you can extend PHP by the power of all available Java classes. To show you the basics of the Java extension, this article will cover installation and a few code examples of using PHP and Java together.

Windows Installation
  The following configuration has been tested with Apache 1.3.12, PHP 4.0.3 binaries from www.php4win.de plus the 4.0.3 Zend Optimiser and JDK 1.2.2 from java.sun.com. We have also tested this configuration with older versions of the JDK and the various MS webservers (PWS and IIS) on Windows 95, Windows 98 and NT4.
  Step 1: Install the JDK. This is fairly simple, as the JDK installs without many questions. It might be useful to check your environment (autoexec.bat in Windows 9x and System under Control Panel in NT) and make sure the jdk1.x.x\bin directory is in your path. This will make compiling your Java Classes easier. On Win9x add

PATH=%PATH%;C:\jdk1.2.2\bin
  to your autoexec.bat. On NT add

;C:\jdk1.2.2\bin
  to the end of the PATH environment variable. It is also important to note in your autoexec.bat file, the PHP Java extension ignores the JAVA_HOME and CLASSPATH set up in the environment. This is important because these items must be set correctly in your php.ini file for the Java extension to work.
  Step 2: Modifying your php.ini. You need to add something similiar to your php.ini file

[java]extension=php_java.dlljava.library.path=c:\web\php4\extensionsjava.class.path="c:\web\php4\extensions\jdk1.2.2\php_java.jar;c:\myclasses"
  Typically, people put the extension=php_java.dll directive with the rest of the extensions, but it can sit happily under [java]. The java.library.path must be set in the location of the php_java.dll, and java.class.path must include the location of php_java.jar. The java.class.path should also include the path to other classes you may wish to use (note the double quotes!). In these examples, we will be talking about c:\myclasses. You should also note that the single period is ignored by PHP and Java. As far as we know, you cannot set PHP to look in the current directory for its Java classes.
  Step 3: Testing your Install. Now, you're ready to go. Create a PHP file that looks something like this:

<?php  $system = new Java("java.lang.System");  print "Java version=".$system->getProperty("java.version")." <br>\n";  print "Java vendor=".$system->getProperty("java.vendor")." <p>\n\n";  print "OS=".$system->getProperty("os.name")." ".              $system->getProperty("os.version")." on ".              $system->getProperty("os.arch")." <br>\n";  $formatter = new Java("java.text.SimpleDateFormat","EEEE, MMMM dd, yyyy 'at' h:mm:ss a zzzz");  print $formatter->format(new Java("java.util.Date"))."\n";  ?>
  NB: This is taken directly from Sam Ruby's examples. If you have correctly installed everything, you should see some results like:

Java version=1.2.2 Java vendor=Sun Microsystems Inc. OS=Windows 95 4.10 on x86 Wednesday, October 18, 2000 at 10:22:45 AM China Standard Time
  A very simple example, but it shows you can access currently available Java classes. Once you have this example working, you have successfully set up the PHP Java extension.

Example 1: Creating and using your own Classes
  Creating your own Java class is pretty easy. Open a new text file called phptest.java. Make sure it is in your java.class.path, as specified in your php.ini file. In that file, enter the following:

public class phptest{ /*** A sample of a class that can work with PHP* NB: The whole class must be public to work,  * and of course the methods you wish to call* directly.** Also note that from PHP the main method * will not be called    */public String foo; /*** Takes a string and returns the result * or a msg saying your string was empty*/public String test(String str) {      if(str.equals("")) {           str = "Your string was empty. ";      }      return str;    }/** * whatisfoo() simply returns the value of the variable foo.*/     public String whatisfoo() {      return "foo is " + foo;    } /** * This is called if phptest is run from the command line with * something like *   java phptest* or*   java phptest hello there*/public static void main(String args[]) {phptest p = new phptest();        if(args.length == 0) {String arg = "";System.out.println(p.test(arg));}else{for (int i=0; i < args.length; i++) { String arg = args;System.out.println(p.test(arg));    }}}}
  Once you have created the file, you want to compile it with javac phptest.java at the command line. This will depend on having the java/bin directory in your PATH environment variable. Once compiled, you can test the class on the command line. Try java phptest, or java phptest hello world. This class is made accessible on the command line, via the main() method. This isn't required for our Java + PHP explorations, but is a nice way to see the class at work.
  To test this new class with PHP, create a new php file on your web server called phptest.php. It should contain the following:
  <?php

$myj
=newJava("phptest");
echo
"TestResultsare<b>".$myj->test("HelloWorld")."</b>";

$myj->foo="AStringValue";
echo
"Youhavesetfooto<b>".$myj->foo."</b><br>\n";
echo
"Myjavamethodreports:<b>".$myj->whatisfoo()."</b><br>\n";

?>

  If you get a Warning: java.lang.ClassNotFoundException error, it simply means your phptest.class file is not in your java.class.path specified in your php.ini file.
  One thing to remember is that Java is strongly typed, and PHP isn't. This could cause problems when Java expects a String, but receives an Integer (or visa-versa). Try replacing the line: $myj->foo = "A String Value"; with $myj->foo = 12345678; and see what happens.
  You should cast your variables to the correct type before passing them to Java. eg: $myj->foo = (string) 12345678; or $myj->foo = "12345678";
  The phptest.java example is a very simple example of how you can create you own Java class and have PHP access to it.

Example 2: Using Xalan 1.2 to transform XML with XSLT
  As another example of accessing Java objects in PHP, we will use the Xalan-java XSLT engine from the Apache XML project. With this application, we can transform XML source files using instructions in a XSL file. This allows for a great number of interesting scenarios in the field of document processing and content management.
  To get started, we need to place both xerces.jar and xalan.jar files (included in Xalan-Java version 1.2 from xml.apache.org) in your java.class.path, as defined in your php.ini file.
  The function xslt_transform() takes XML and XSL files as parameters and returns the transformed output in a string. XML and XSL parameters can be filenames (eg. foo.xml) or fully resolved URI's (eg. http://localhost/foo.xml).
  <?php

functionxslt_transform($xml,$xsl){

//CreateaXSLTProcessorFactoryobject.XSLTProcessorfactoryisaJava
//classwhichmanufacturestheprocessorforperformingtransformations.
$XSLTProcessorFactory=newjava("org.apache.xalan.xslt.XSLTProcessorFactory");

//UsetheXSLTProcessorFactorymethodgetProcessor()tocreatea
//newXSLTProcessorobject.
$XSLTProcessor=$XSLTProcessorFactory->getProcessor();

//UseXSLTInputSourceobjectstoprovideinputtotheXSLTProcessor
//process()methodfortransformation.Createobjectsforboththe
//xmlsourceaswellastheXSLinputsource.Parameterof
//XSLTInputSourceis(inthiscase)a'systemidentifier'(URI)which
//canbeanURLorfilename.IfthesystemidentifierisanURL,it
//mustbefullyresolved.
$xmlID=newjava("org.apache.xalan.xslt.XSLTInputSource",$xml);
$stylesheetID=newjava("org.apache.xalan.xslt.XSLTInputSource",$xsl);

//CreateastringWriterobjectfortheoutput.
$stringWriter=newjava("java.io.StringWriter");

//CreateaResultTargetobjectfortheoutputwiththeXSLTResultTarget
//class.ParameterofXSLTResultTargetis(inthiscase)a'character
//stream',whichisthestringWriterobject.
$resultTarget=newjava("org.apache.xalan.xslt.XSLTResultTarget",$stringWriter);

//ProcessinputwiththeXSLTProcessors'methodprocess().This
//methodusestheXSLstylesheettotransformtheXMLinput,placing
//theresultintheresulttarget.
$XSLTProcessor->process($xmlID,$stylesheetID,$resultTarget);

//UsethestringWriters'methodtoString()to
//returnthebuffer'scurrentvalueasastringtogetthe
//transformedresult.
$result=$stringWriter->toString();
$stringWriter->close();
return(
$result);
}

?>

  Then, you can call this function as shown in the example below. $xml contains a string with the fully resolved URL of XML file. $xsl contains string with a XSL stylesheet URL containing rules for conversion to generic HTML. $out will contain a string with output, as a result of calling xslt_transform described above. This example parses a XML newsfeed containing the 5 latest articles on phpbuilder.com. You are encouraged to also try other XML feeds and/or XSl stylesheets.
  <?php

$xml
="http://www.phpbuilder.com/rss_feed.php?type=articles&limit=5";
$xsl="http://www.soeterbroek.com/code/xml/rss_html.xsl";
$out=xslt_transform($xml,$xsl);
echo
$out;

?>

  If you are processing local files, make sure you use the full path name to pass to the Java class.
  <?php

$xml
="/web/htdocs/xml_java/rss_feed.xml";
$xsl="/web/htdocs/xml_java/rss_html.xsl";
$out=xslt_transform($xml,$xsl);
echo
$out;

?>

  Although there are a number of other ways in PHP to achieve the same results, the above example gives you a good idea of the possibilities of accessing Java objects in PHP.

Conclusion
  Using the PHP Java extensions allows you to extend your PHP code, via all the Java class's now available. Some potential uses are;
1. Use PHP to send a fax, via the Hylafax Javaclient http://www.hylafax.org/
2. Use PHP to access your Remedy application http://www.tek-tools.com/jticket/
3. Use PHP to generate bar codes, via a Java Barcode class
4. Convert your Applets so that they can generate a GIF / JPG to display to non Java browsers

In the next article on Java and PHP, we hope to show how to set up PHP with Java on a Linux box, Error checking, show you how to generate a JPG file from a Java class and use some classes readily available on the Web.
  -- Mark
-- Joost
and thanks to Sam Ruby for producing such an interesting extension to PHP!

Useful Links
  http://www.php4win.de ~ A great Win32 distribution of PHP
http://www.javasoft.com ~ Sun's Java release
http://www.jars.com ~ Start searching for handy Java classes
http://www.gamelan.com ~ More Java classes
http://www.technetcast.com/tnc_play_stream.html?stream_id=400 ~ Sam Ruby about PHP and Java integration at Open Source Convention 2000 (audio)
http://xml.apache.org ~ Apache XML Project
http://www.phpbuilder.com/columns/justin20001025.php3 ~ Transforming XML with XSL using Sablotron

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-349539-1-1.html 上篇帖子: PHP 函数 下篇帖子: php初学
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表