I have the following PHP code, but it's not working. I don't see any errors, but maybe I'm just blind. I'm running this on PHP 5.3.1.
<?php
$xsl_string = <<<HEREDOC
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
extension-element-prefixes="exsl">
<xsl:template match="/">
<p>Hello world</p>
<xsl:variable name="person">
<firstname>Foo</firstname>
<lastname>Bar</lastname>
<email>[email protected]</email>
</xsl:variable>
<xsl:value-of select="exsl:node-set(\$person)/email"/>
</xsl:template>
</xsl:stylesheet>
HEREDOC;
$xml_dom = new DOMDocument("1.0", "utf-8");
$xml_dom->appendChild($xml_dom->createElement("dummy"));
$xsl_dom = new DOMDocument();
$xsl_dom->loadXML($xsl_string);
$xsl_processor = new XSLTProcessor();
$xsl_processor->importStyleSheet($xsl_dom);
echo $xsl_processor->transformToXML($xml_dom);
?>
This code should output "Hello world" followed by "[email protected]", but the e-mail portion doesn't appear. Any idea what's wrong?
-Geoffrey Lee
The problem is that the provided XSLT code has a default namespace.
Therefore, the <firstname>
, <lastname>
and <email>
elements are in the xhtml namespace. But email
is referenced without any prefix in:
exsl:node-set($person)/email
XPath considers all unprefixed names to be in "no namespace". It tries to find a child of exsl:node-set($person)
called email
that is in "no namespace" and this is unsuccessful, because its email
child is in the xhtml namespace. Thus no email
node is selected and output.
Solution:
This transformation:
<xsl:stylesheet version="1.0"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:x="http://www.w3.org/1999/xhtml"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
exclude-result-prefixes="exsl x">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/">
<html>
<p>Hello world</p>
<xsl:variable name="person">
<firstname>Foo</firstname>
<lastname>Bar</lastname>
<email>[email protected]</email>
</xsl:variable>
<xsl:text>
</xsl:text>
<xsl:value-of select="exsl:node-set($person)/x:email"/>
<xsl:text>
</xsl:text>
</html>
</xsl:template>
</xsl:stylesheet>
when applied on any XML document (not used), produces the wanted result:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:x="http://www.w3.org/1999/xhtml">
<p>Hello world</p>
[email protected]
</html>
Do note:
The added namespace definition with prefix x
The changed select
attribute of <xsl:value-of>
:
exsl:node-set($person)/x:email
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With