XSLT - On the Server Side
Since not all browsers support XSLT, another solution is to perform the XML-to-XHTML transformation on the server.
Cross-Browser Solution
In the previous chapter, we explained how to use XSLT in the browser to transform XML into XHTML. We created a piece of JavaScript that uses an XML parser to perform the transformation. The JavaScript solution does not work in browsers without an XML parser.
To make XML data suitable for any type of browser, we must transform the XML document on the server and then send it back to the browser as XHTML.
This is another advantage of XSLT. One of the design goals of XSLT is to make it possible to transform data from one format to another on the server and return readable data to all types of browsers.
The XML File and the XSLT File
Look at this XML document shown in the previous chapter:
Empire Burlesque
Bob Dylan
USA
Columbia
10.90
1985
.
.
and the accompanying XSL stylesheet:
My CD Collection
Title
Artist
Note that this XML file does not contain a reference to the XSL file.
**Important:** The above statement means that an XML file can be transformed using multiple different XSL stylesheets.
Transforming XML into XHTML on the Server
This is the source code used to transform an XML file into XHTML on the server:
Transform using PHP code:
load('cdcatalog.xml');
// Load XSL file
$xsl = new DOMDocument;
$xsl->load('cdcatalog.xsl');
// Set conversion
$proc = new XSLTProcessor;
// Add xsl rules
$proc->importStyleSheet($xsl);
echo $proc->transformToXML($xml);
?>
**Tip:** If you do not know how to write PHP, you can study our PHP Tutorial。
Transform using ASP code:
<%
'载入 XML 文件
set xml = Server.CreateObject("Microsoft.XMLDOM")
xml.async = false
xml.load(Server.MapPath("cdcatalog.xml"))
'载入 XSL 文件
set xsl = Server.CreateObject("Microsoft.XMLDOM")
xsl.async = false
xsl.load(Server.MapPath("cdcatalog.xsl"))
'转换文件
Response.Write(xml.transformNode(xsl))
%>
**Tip:** If you do not know how to write ASP, you can study our ASP Tutorial。
The first piece of code creates an instance of Microsoft's XML parser (XMLDOM) and loads the XML file into memory. The second piece creates another instance of the parser and loads the XSL file into memory. The last line uses the XSL document to transform the XML document and sends the result to your browser as XHTML. Great!