2

Is it possible to use PHP within an XSL document?

Always when I try to do so I get errors... so before freaking out I'd like to know whether or not it's even possible. (I am an absolute beginner)

I have an XSL file like this one

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE xsl:stylesheet [
<!ENTITY nbsp "&#160;">
]>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
 <head>
  <title></title>

   <style type="text/css">
    [...]
   </style>

 </head>
 <body>

[...]

  <div id="content">
   <?php echo $anything; ?>
  </div>

[...]

 </body>
</html>
</xsl:template>

</xsl:stylesheet>

(I cut the code)

So I am including the XML file via PHP (that XML file is styled with this XSL file) And now I tried to echo the content of for example $anything

But it doesn't work

2
  • Please specify, how do you try it. Commented Sep 25, 2009 at 22:13
  • Which errors? What are you trying to do exactly, and why in this way over another? Commented Sep 25, 2009 at 22:13

4 Answers 4

2

If you'll use the XSLTProcessor class to do your XSL, you can just registerPHPFunctions. I do it all the time for certain data manipulations within the XSL. Then I can call any PHP function or method I want in the XSL.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use it in both the xsl an the xml it is transforming.

  • Your server must parse .xsl/.xml files as php
  • Your php must generate valid xsl/xml

1 Comment

How is it used in the XML being transformed?
1

If you're running Saxon-EE 9.7 XSLT processor, then you can use the <xsl:processing-instruction name="php"> as your <?php tag with one quirky caveat: you have to add the ? immediately before the closing </xsl:processing-instruction> tag.

<xsl:processing-instruction name="php">
    echo "hello world!";
?</xsl:processing-instruction>

To use your example, it would look like this:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE xsl:stylesheet [
<!ENTITY nbsp "&#160;">
]>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
 <head>
  <title></title>

   <style type="text/css">
    [...]
   </style>

 </head>
 <body>

[...]

  <div id="content">

        <xsl:processing-instruction name="php">
            echo $anything;
        ?</xsl:processing-instruction>

  </div>

[...]

 </body>
</html>
</xsl:template>

</xsl:stylesheet>

Comments

0

You can use simplexml to manipulate the XML in PHP. http://nl.php.net/simplexml there's the reference of the simplexml class. So after you load the XML file into PHP and before echoing it using the asXML()-function, you can alter the XML through the simplexml interface.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.