Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Using XSL with PHP and passing Values

XSLT and XML

Using XSL with PHP and passing Values

by  Karl Blessing  Posted    (Edited  )
This issue came up because I had a single XML document, and in one of the sections I had to output the list of items if none were specificed, and if one was specificed to only output that node. So this FAQ simply covers how to transform XML w/ XSL documents into a usable state, but also how to take data from PHP and pass them into the XSL parser.

Code:
// Xml and XSL files
$xml_file = "./sections/sitedata.xml";
$xsl_file = "./sections/".$page.".xsl";

//Check for Extra Parameters
$xtra = "A Value;"
/* you can also give multiple by changing $xtra into $xtra = array("name" => "value", "name2" => "value2"); then changing out the array('xtra' => $xtra) to just $xtra. */

// Allocate a new XSLT processor
$xh = xslt_create();
$fileBase = 'file://' . getcwd () . '/';
xslt_set_base ( $xh, $fileBase );
				
// Process the document
					
$result = xslt_process($xh, $xml_file, $xsl_file, NULL, array(), array('xtra' => $xtra));
if (!$result) {
    // Something croaked. Show the error
    echo 'XSLT processing error: ' .xslt_error($xh) ;
}

Then in the XSL stylesheet:

Code:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xsl:space="preserve">

<xsl:param name="xtra"/>

<xsl:template match="/">
	<xsl:apply-templates select="sitedata" />
</xsl:template>
....

Thats the declaration above. To actually obtain or use the value:

Before PHP 4.0.6
Code:
<xsl:value-of select="xtra" />

PHP 4.0.6 and newer
Code:
<xsl:value-of select="$xtra" />

In the way I used this if I only wanted it to show the tutorial I've passed a value for would be something like this:

Code:
<xsl:template match="tutorial">
<xsl:if test="./@id=$xtra">
....
      OUTPUT for this tutorial
....
</xsl:if>
</xsl:template>
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top