Passing Parameters to an XSLT Stylesheet

I l @ ve RuBoard

If you need to pass data from the PHP script to the XSLT stylesheet, PHP's xslt_process() function can be used to pass an associative arrays of parameters to the XSLT stylesheet.

You'll remember that the xslt_process() function can accept an array containing parameter-value pairs as an optional sixth argument. These parameters can be passed on to the stylesheet and used within template rules.

Consider Listing 4.8, which creates an associative array named $params , and stores two elements containing the page title and current date in it. This associative array is then passed on to the stylesheet via the xslt_process() function.

Listing 4.8 Passing Parameters to an XSLT Stylesheet
 <?php  // set the filenames  $xml_file = "aloha.xml";  $xslt_file = "aloha.xsl";  // set up the parameters  $params = array("today" => date("d M Y", mktime()), "page_title" => "Aloha!");  // include an empty array for arguments (otherwise XSLT tends to break - hopefully graphics/ccc.gif corrected in next release)  $arg_buffer = array();  // create the XSLT processor  $xp = xslt_create() or die("Could not create XSLT processor");  // process the two files to get the desired output  if($result = xslt_process($xp, $xml_file, $xslt_file, NULL, $arg_buffer, $params))  {       echo $result;  }  else  {       echo "An error occurred: " . xslt_error($xp) . "(error code " . xslt_errno($xp) . graphics/ccc.gif ")";  }  // free the resources occupied by the handler  xslt_free($xp);  ?> 

These parameters are now available to the stylesheet and can be used within a template rule via the <xsl:param /> element (see Listing 4.9).

Listing 4.9 Using Passed Parameters in an XSLT Stylesheet
 <?xml version="1.0"?>  <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">  <!-- define the parameter -->  <xsl:param name="page_title"/>  <xsl:param name="today"/>  <xsl:template match="/">        <html>        <head>          <!-- use the parameter -->        <title><xsl:value-of select="$page_title" /> Today is <xsl:value-of select="$today" graphics/ccc.gif /> </title>        </head>        <body>        <!-- other templates - snip! -->        </body>        </html>  </xsl:template>  </xsl:stylesheet> 
I l @ ve RuBoard


XML and PHP
XML and PHP
ISBN: 0735712271
EAN: 2147483647
Year: 2002
Pages: 84

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net