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.dll
java.library.path=c:\web\php4\extensions\
java.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[i];
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 = 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";
?>
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
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);
}
?>
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