当前位置:首页> PHP教程> PHP精通
关键字
文章内容
如何使用PHP调用JAVA类库
 
 
修改时间:[2010/08/10 21:06]    阅读次数:[932]    发表者:[起缘]
 
JAVA是个非常强大的编程利器,它的扩展库也是非常的有用,这篇教程,主要讲述怎样使用PHP调用功能强大的JAVA 类库(classes)。为了方便你的学*,这篇教程将包括JAVA的安装及一些基本的例子。

windows下的安装

第一步:安装JDK,这是非常容易的,你只需一路回车的安装好。然后做好以下步骤。
在 Win9x 下加入 :“PATH=%PATH%;C:jdk1.2.2in” 到AUTOEXEC.BAT文件中
在 NT 下加入 “;C:jdk1.2.2in”到环境变量中。

这一步是非常重要的,这样PHP才能正确的找到需调用的JAVA类。

第二步:修改你的PHP.INI文件。
[java]
extension=php_java.dll
java.library.path=c:webphp4extensions
java.class.path="c:webphp4extensionsjdk1.2.2php_java.jar;c:myclasses"

在PHP.INI中加入extension=php_java.dll
并在[java]中,设定好java.class.path,让它指向php_java.jar,如果你使用新的JAVA类,你也应该存入这个路径,在这篇例子中,我们使用c:myclasses这个目录。

第三步:测试环境,创建如下PHP文件:
<?php

$system = new Java("java.lang.System");
print "Java version=".$system->getProperty("java.version")." <br> ";
print "Java vendor=".$system->getProperty("java.vendor")." <p> ";
print "OS=".$system->getProperty("os.name")." ".
$system->getProperty("os.version")." on ".
$system->getProperty("os.arch")." <br> ";

$formatter = new Java("java.text.SimpleDateFormat","EEEE,
MMMM dd, yyyy ´at´ h:mm:ss a zzzz");
print $formatter->format(new Java("java.util.Date"))." ";

?>

如果你正确安装了,你将会看到以下信息:

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

这样,我们就已经成功的建立起了可以使用JAVA类的PHP运行环境,我们可以开始我们接下去的课程了。
例子1:创建和使用你自己的JAVA类
创建你自己的JAVA类非常容易。新建一个phptest.java文件,将它放置在你的java.class.path目录下,文件内容如下:

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[i];
System.out.println(p.test(arg));
}
}
}
}

创建这个文件后,我们要编译好这个文件,在DOS命令行使用javac phptest.java这个命令。

为了使用PHP测试这个JAVA类,我们创建一个phptest.php文件,内容如下:

<?php

$myj = new Java("phptest");
echo "Test Results are <b>" . $myj->test("Hello World") . "</b>";

$myj->foo = "A String Value";
echo "You have set foo to <b>" . $myj->foo . "</b><br>n";
echo "My java method reports: <b>" . $myj->whatisfoo() . "</b><br>n";

?>

如果你得到这样的警告信息:java.lang.ClassNotFoundException error ,这就意味着你的phptest.class文件不在你的java.class.path目录下。
注意的是JAVA是一种强制类型语言,而PHP不是,这样我们在将它们融合时,容易导致错误,于是我们在向JAVA传递变量时,要正确指定好变量的类型。如:$myj->foo = (string) 12345678; or $myj->foo = "12345678";

这只是一个很小的例子,你可以创建你自己的JAVA类,并使用PHP很好的调用它!
例子二:通过Xalan 1.2,使用XSLT转换XML

做为第二个例子,我们使用了Xalan-java的XSLT引擎,这个引擎来自于APACHE的XML项目,使用这个程序,我们能够使用XSL转换XML源文件。这将极大的方便我们处理文档和进行内容管理。

开始之前,我们需要将xerces.jar 和 xalan.jar文件放入java.class.path目录下(这两个文件包含在Xalan-Java 1.2 中,可以从xml.apache.org处下载)。
PHP程序如下:
函数xslt_transform()以XML和XSL文件为参数,形式可为文件名(如:foo.xml)或URL(如:http://localhost/foo.xml)。

<?php

function xslt_transform($xml,$xsl) {

// Create a XSLTProcessorFactory object. XSLTProcessorfactory is a Java
// class which manufactures the processor for performing transformations.
$XSLTProcessorFactory = new java("org.apache.xalan.xslt.XSLTProcessorFactory");

// Use the XSLTProcessorFactory method getProcessor() to create a
// new XSLTProcessor object.
$XSLTProcessor = $XSLTProcessorFactory->getProcessor();

// Use XSLTInputSource objects to provide input to the XSLTProcessor
// process() method for transformation. Create objects for both the
// xml source as well as the XSL input source. Parameter of
// XSLTInputSource is (in this case) a ´system identifier´ (URI) which
// can be an URL or filename. If the system identifier is an URL, it
// must be fully resolved.
$xmlID = new java("org.apache.xalan.xslt.XSLTInputSource", $xml);
$stylesheetID = new java("org.apache.xalan.xslt.XSLTInputSource", $xsl);

// Create a stringWriter object for the output.
$stringWriter = new java("java.io.StringWriter");

// Create a ResultTarget object for the output with the XSLTResultTarget
// class. Parameter of XSLTResultTarget is (in this case) a ´character
// stream´, which is the stringWriter object.
$resultTarget = new java("org.apache.xalan.xslt.XSLTResultTarget", $stringWriter);

// Process input with the XSLTProcessors´ method process(). This
// method uses the XSL stylesheet to transform the XML input, placing
// the result in the result target.
$XSLTProcessor->process($xmlID,$stylesheetID,$resultTarget);

// Use the stringWriters´ method toString() to
// return the buffer´s current value as a string to get the
// transformed result.
$result = $stringWriter->toString();
$stringWriter->close();
return($result);
}

?>

函数定义好后,我们就可以调用它了,在下面的例程中,变量$xml指向一个URL字符串,$xsl也是如此。这个例子将显示5个最新的phpbuilder.com文章标题。

<?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;

?>

如果你在本地机上运行程序,必须确保你的函数参数指向正确的文件名。

<?php

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

?>

虽然这种效果我们可以通过其它方法实现,或许那些方法更好,但这个例子能让你对PHP调用JAVA类有一个更好的了解。

教程结束了,希望你能够从这篇教程中学到点东西,以下是一些你用得到的链接:
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