XSL and XSLT Page 42
March 22, 2002
The XML document, travel.xml, is the same file that we've been
using throughout this chapter. travel.xsl is the file that
contains the XSL stylesheet. travel.php is the file that has the
PHP code that loads the XML and XSL files, calls the processor,
and returns the result as HTML to the browser.
In the previous code examples the bulk of the work displaying
the XML as an HTML table was done using PHP. In this example,
the bulk of the work is done using XSL. Consequently, the XSL
file is the largest of the three files used in this example.
travel.xsl is shown below. This file has two main sections, the
head (or top-level) and the body of the document. In the head we
define the version and namespace information for the file
The body of the document starts with the <xsl:output>
line. The structure of the body for this XSL consists of
instructions to match parts of the XML document and descriptions
of the formatting for that match. First we look for and match
/Recordset. As Recordset is the root element,
we can use it to identify the start of the XML file. As we want
to have the contents of the XML file displayed as an HTML table,
we use the Recordset element as a identifier of the start of the
file. So we put the opening HTML in this section, like the
<title>, <head>, and <body> tags:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
The following line creates a <meta> tag in the subsequent
HTML file that looks like this: <meta http-
equiv="Content-Type" content="text/html;
charset=utf-8">:
<xsl:output encoding="utf-8"
method="html" indent="yes" />
As Recordset is the root element, we use it as the start
of our HTML file:
<xsl:template match="/Recordset">
<html>
<head>
<title>XSL Travel</title>
</head>
<body>
<h1>Travel Packages</h1>
<table border="0">
We use a xsl:for-each statement to loop through both the
instances of in the travel.xml
file. Everything within the for-each loop is basically the same.
We start a table row and populate it with the element name and
value of that element.
The use of <xsl:text> isn't necessary in this code, but it
is good practice to use it. The following samples in the XSL
produce the same results on the screen:
Sample 1
<td>
Country_name
</td>
Sample 2
<td>
<xsl:text>Country_name</xsl:text>
</td>
Sample 3
<td>
<xsl:text>
Country_name
</xsl:text>
<td>
However, Sample 3 produces different HTML. Sample 1 and Sample 2
produce HTML with no whitespace (one long line of HTML), whereas
Sample 3 has whitespace in the form of a carriage return after
the <td> and Country_name.
XSL and XSLT Page 41
Professional PHP4 Programming
XSL and XSLT Page 43
|