PHP XML
Setting XSLT Parameters from PHP
Problem
You want to set parameters in your XSLT stylesheet from PHP.
Solution
Use the XSLTProcessor::setParameter() method:
// This could also come from $_GET['city'];
$city = 'San Francisco';
$dom = new DOMDocument;
$dom->load(__DIR__ . '/address-book.xml');
$xsl = new DOMDocument;
$xsl->load(__DIR__ . '/stylesheet.xsl');
$xslt = new XSLTProcessor();
$xslt->importStylesheet($xsl);
$xslt->setParameter(NULL, 'city', $city);
print $xslt->transformToXML($dom);
This code sets the XSLT city parameter to the value stored in the PHP variable $city.
Discussion
You can pass data from PHP into your XSLT stylesheet with the setParameter() method. This allows you to do things such as filter data in your stylesheet based on user input.
For example, this program allows you to find people based on their city:
// This could also come from $_GET['city'];
$city = 'San Francisco';
$dom = new DOMDocument;
$dom->load(__DIR__ . '/address-book.xml');
$xsl = new DOMDocument;
$xsl->load(__DIR__ . '/stylesheet.xsl');
$xslt = new XSLTProcessor();
$xslt->importStylesheet($xsl);
$xslt->setParameter(NULL, 'city', $city);
print $xslt->transformToXML($dom);
The program uses the following stylesheet:
<?xml version="1.0" ?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/address-book/person">
<xsl:if test="city=$city">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
The program and stylesheet combine to produce the following results:
<?xml version="1.0"?>
<address-book>
<person id="2">
<!--Adam Trachtenberg-->
<firstname>Adam</firstname>
<lastname>Trachtenberg</lastname>
<city>San Francisco</city>
<state>CA</state>
<email>amt@php.net</email>
</person>
</address-book>
The PHP script does a standard XSLT transformation, except it calls $xslt->setParameter(NULL, city, $city). The first argument is the parameter’s name‐space, the second is the parameter’s name, and the third is the parameter’s value.
Here, the value stored in the PHP variable $city—in this case, San Francisco—is assigned to the XSLT parameter city, which does not live under a namespace. This is equal to placing the following in an XSLT file:
<xsl:param name="city">San Francisco</xsl:param>
You usually access a parameter inside a stylesheet like you do a PHP variable, by placing a dollar sign ($) in front of its name. The stylesheet example creates a template that matches /address-book/person nodes.
Inside the template, you test whether city=$city; in other words, is the city child of the current node equal to the value of the city parameter? If there’s a match, the children are copied along; otherwise, the records are eliminated.
In this case, city is set to San Francisco, so David’s record is removed and Adam’s remains.
No comments:
Post a Comment