Use PHP's DOM and XSLT extensions together:
- <?php
- // read XML data
- $xml = new DOMDocument;
- $xml->load('review.xml');
- // read XSL stylesheet data
- $xsl = new DOMDocument;
- $xsl->load('review.xsl');
- // initialize XSLT engine
- $xslp = new XSLTProcessor;
- // attach XSL stylesheet object
- $xslp->importStyleSheet($xsl);
- // perform transformation
- echo $xslp->transformToXML($xml);
- ?>
Comments
XSL, the Extensible Style Language, is a powerful language that makes it possible to apply presentation rules to XML documents, and convert—or transform—them from one format to another. For example, you could use different XSL transformations to create an HTML Web page, a WML deck, and an ASCII text file… all from the same source XML.
An XSL Transformation essentially consists of converting an XML source tree into a new—and usually completely different—result tree. This is accomplished by means of an XSLT stylesheet, which contains one or more template rules. A template rule performs two functions: It first identifies a pattern to match in the source tree, and then describes the structure of the desired result tree. It is this process of transforming the source tree into the result tree that gives XSLT its name.
The previous listing demonstrates how this works in PHP. Here, two instances of the DOMDocument class are created, one for the XML data and the other for the XSLT style sheet. Next, the XSLT engine is initialized by creating an object of the XSLTProcessor class, and the object's importStyleSheet() method is used to import the XSLT style sheet. Once the style sheet has been successfully parsed, the transformToXML() method is used to apply the style rules to the XML document, "transform" it, and return the result.