tags:

views:

95

answers:

1

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

+2  A: 

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>&#xA;</xsl:text>
     <xsl:value-of select="exsl:node-set($person)/x:email"/>
     <xsl:text>&#xA;</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"&gt;
   <p>Hello world</p>
[email protected]
</html>

Do note:

  1. The added namespace definition with prefix x

  2. The changed select attribute of <xsl:value-of>:

exsl:node-set($person)/x:email

Dimitre Novatchev
Ah, that makes complete sense now. Thank you for your well-written answer!
geofflee