Getting XSL to work

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Getting XSL to work

Post by anjanesh »

Im trying to use DOM and XSL to produce output

Code: Select all

$xml = new DOMDocument;
$xml->loadXML($str_xml);

$xsl = new DOMDocument;
$xml->load($xsl_filename);

$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl);
But in my XSL document, how do I insert an XSL tag within normal html attribute values ?

Code: Select all

....
<td><img src='<xsl:value-of select="img"/>' alt="logo" style="width:196px; height:196px" /></td>
<td><xsl:value-of select="message"/></td>
...
Thanks
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

By either using xsl:attribute or the {} shortcut.

Code: Select all

<?php
$xml = '<root>
  <leaf attr="A">I</leaf>
  <leaf attr="B">II</leaf>
  <leaf attr="C">III</leaf>
</root>';

$xsl = '<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns="http://www.w3.org/1999/xhtml">
  
  <xsl:template match="leaf">
    <!-- long version -->
    <img>
      <xsl:attribute name="src"><xsl:value-of select="@attr" /></xsl:attribute>
    </img>
    
    <!-- short version -->
    <img src="{@attr}" />
  </xsl:template>
  
  <xsl:template match="/">
    <xsl:apply-templates />
  </xsl:template>
</xsl:stylesheet>';

$xml = DOMDocument::loadXML($xml);

$xsl = DOMDocument::loadXML($xsl);

$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); 
echo $proc->transformToXML($xml);
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Post by anjanesh »

Thanks volka. I guess the long version is more readable in the long run.

I was going through the html-source and the img tag wasnt closed. <img src="">
How do I get it to close the tag ? <img src=""/>

EDIT : In the XSL file, use
<xsl:output method="xml" encoding="iso-8859-1" indent="no"/>
instead of
<xsl:output method="html" encoding="iso-8859-1" indent="no"/>

[ Though default is taken as XML if none is specified ]
Post Reply