HomeXML Page 5 - XSL Transformation With PHP And Sablotron
An Evening At The Moulin Rouge - XML
So you've got your XML, and you've also got an XSLT stylesheet to format it. But how do you put the two of them together? Fear not - you can use PHP's Sablotron extension to perform XSLT transformation of XML data on the server. This article tells you how.
What you've just seen is a generic way to process XML data with PHP. It isn't the only one, though; for larger, more complex files, PHP offers yet another method of applying an XSLT stylesheet to your XML.
<body>
A stylishly spectacular extravaganza, <title>Moulin Rouge</title>
is hard
to categorize; it is, at different times, a love story, a costume drama,
a
musical, and a comedy. Director <person>Baz Luhrmann</person> (well-known
for
the very hip <title>William Shakespeare's Romeo + Juliet</title>) has
taken
some simple themes - love, jealousy and obsession - and done
something completely
new and different with them by setting them to music.
</body>
<rating>5</rating>
<teaser>Baz Luhrmann's over-the-top
vision of Paris at the turn of the
century
is witty, sexy...and completely unforgettable</teaser>
</review>
And the corresponding XSLT stylesheet to transform this information into a simple
Web page:
The xslt_output_begintransform() function is a special function which take only
one parameter: the location of the XSLT file. Once this function is invoked, the XSLT processor will transform all the content that it encounters as per the rules in the named file until it's told to stop via the function xslt_output_endtransform().
In this case, I've written a simple "for" loop to iterate through the elements of the XML array, printing each element as it finds it. The XSLT processor will transform this output as it is printed, providing the desired result.
This technique comes in particularly handy if you don't have your XML data in a static file, but generate it dynamically - say, from a database, or by combining multiple XML documents into a single file. You can write PHP code to obtain the data and massage it into an XML-compliant format, and then enclose that code in calls to xslt_output_begintransform() and xslt_output_endtransform() to transform it.