i am trying to output the Form using XML & XSLT in php but i am unable to fullfill the condition somehow.here is what my XML look like:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="form.xsl"?>
<root>
<formset>
<field>
<type>text</type>
<value>This is test value</value>
</field>
<field>
<type>radio</type>
<value>Male</value>
</field>
<field>
<type>checkbox</type>
<value>Hobby</value>
</field>
<field>
<type>button</type>
<value>Click Me</value>
</field>
</formset>
</root>
and Here is my XSLT file:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<head>
<title>Rendering of Form</title>
</head>
<body>
<form action="" method="post">
<xsl:for-each select="/root/formset/field">
<xsl:choose>
<xsl:when test="type = text">
<input type="text" value="{value}" />
</xsl:when>
<xsl:when test="type = radio">
<input type="radio" value="{value}" /> <xsl:value-of select="value"/>
</xsl:when>
<xsl:when test="type = checkbox">
<input type="checkbox" value="{value}" /> <xsl:value-of select="value"/>
</xsl:when>
<xsl:when test="type = button">
<input type="button" value="{value}" />
</xsl:when>
<xsl:otherwise>
<span>Unknown Type</span>
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</form>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
my PHP code is this simple echo the output:
<?php
// LOAD XML FILE
$XML = new DOMDocument();
$XML->load('form.xml');
// START XSLT
$xslt = new XSLTProcessor();
$XSL = new DOMDocument();
$XSL->load('form.xsl');
$xslt->importStylesheet( $XSL );
echo $xslt->transformToXML( $XML );
?>
but somehow my output renders xsl:otherwise condition can anyone tell me why ?? i am new to XSLT
This is not actually to do with PHP, but simply to do with the fact you have missed out some apostrophes in your xsl:when test statements. You are currently doing this
But this is comparing an element called type against an element called text, which doesn’t actually exist in your XML. You need to do this instead
i.e. You need to compare against a literal string, enclosed in apostrophes.
If you are keen to learn XSLT, here is a way to do the same thing without the need for xsl:for-each of xsl:choose
Using templates in this way is usually preferred as it helps re-use code, and cuts down on indentation to make it more readable. Note that the more specific template will always get chosen first when matching elements.