PHP & JAVA (3)

zhaozj2021-02-08  419

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 (include 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).

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.xslt.xsltinputSource", $ XML); $ stylesheetid = new java ("org.apache.xalan.xslt .XsltinputSource ", $ XSL); // Create A StringWriter Object t 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.

If you are processing local files, makess.

Although theere a Number of International 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.

转载请注明原文地址:https://www.9cbs.com/read-473.html

New Post(0)