日期:2014-03-07  浏览次数:20485 次

PHP是不少在Web开发领域奋战的勇士们所选用的武器,因为它是一种很直观的编程语言,有强大的函数,良好的跨平台兼容性,还有它是免费的。从网上的小商店到大型企业的网站都能看到PHP的影子。


PHP有一点特性经常被人们忽视,那就是和XSL stylesheets合作对XML进行解析的能力。下面就让我们来看看怎样在PHP中设置一个XSL解析器以及你该如何使用这一功能。


例子
列表A是一个简单的订单文档,我们会将这个文档输入XSL解析器。同时,列表B中的XSL stylesheet也会被输入XSL解析器。

Listing A: order.xml

<?xml version="1.0" ?>
<Order>
<Account>9900234</Account>
<Item id="1">
<SKU>1234</SKU>
<PricePer>5.95</PricePer>
<Quantity>100</Quantity>
<Subtotal>595.00</Subtotal>
<Description>Super Widget Clamp</Description>
</Item>
<Item id="2">
<SKU>6234</SKU>
<PricePer>22.00</PricePer>
<Quantity>10</Quantity>
<Subtotal>220.00</Subtotal>
<Description>Mighty Foobar Flange</Description>
</Item>
<Item id="3">
<SKU>9982</SKU>
<PricePer>2.50</PricePer>
<Quantity>1000</Quantity>
<Subtotal>2500.00</Subtotal>
<Description>Deluxe Doohickie</Description>
</Item>
<Item id="4">
<SKU>3256</SKU>
<PricePer>389.00</PricePer>
<Quantity>1</Quantity>
<Subtotal>389.00</Subtotal>
<Description>Muckalucket Bucket</Description>
</Item>
<NumberItems>1111</NumberItems>
<Total>3704.00</Total>
<OrderDate>07/07/2002</OrderDate>
<OrderNumber>8876</OrderNumber>
</Order>
Listing B: order.xsl

<?xml version="1.0" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="column" select="'SKU'"/>
<xsl:param name="order" select="'ascending'"/>
<xsl:template match="/">
<html>
<body>
<xsl:apply-templates select="Order">
<xsl:with-param name="sortcolumn" select="$column" />
<xsl:with-param name="sortorder" select="$order" />
</xsl:apply-templates>
</body>
</html>
</xsl:template>

<xsl:template match="Order">
<xsl:param name="sortcolumn" />
<xsl:param name="sortorder" />
<table border="1">
<tr>
<th>Account</th>
<th>SKU</th>
<th>Description</th>
<th>Price</th>
<th>Quantity</th>
<th>Subtotal</th>
</tr>
<xsl:apply-templates select="Item">
<xsl:sort select="*[name()=$sortcolumn]" order="{$sortorder}" />
</xsl:apply-templates>
</table>
</xsl:template>

<xsl:template match="Item">
<tr>
<td><xsl:value-of select="../Account" /></td>
<td><xsl:value-of select="SKU" /></td>
<td><xsl:value-of select="Description" /></td>
<td><xsl:value-of select="PricePer" /></td>
<td><xsl:value-of select="Quantity" /></td>
<td><xsl:value-of select="Subtotal" /></td>
</tr>
</xsl:templa