Home

PHP/XSL Snippet: Replacing line breaks with <br>

Published on 18 Oct 2010. Tagged with php.

<?php

$xmlCode = <<<EOT
<test>Ein Zeilenumbruch...
...und noch einer...
...und Schluss.</test>
EOT;

$xslCode = <<<'EOT'
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">  

  <xsl:template name="replace">
    <xsl:param name="string"/>
    <xsl:param name="from"/>
    <xsl:param name="to"/>
    <xsl:choose>
      <xsl:when test="contains($string, $from)">
        <xsl:value-of select="substring-before($string, $from)"/>
        <xsl:copy-of select="$to"/>
        <xsl:call-template name="replace">
          <xsl:with-param name="string"
                          select="substring-after($string, $from)"/>
          <xsl:with-param name="from" select="$from"/>
          <xsl:with-param name="to" select="$to" />
        </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="$string" />
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <xsl:template match="test">
    <p>
      <xsl:call-template name="replace">
        <xsl:with-param name="string" select="."/>
        <xsl:with-param name="from" select="'&#xA;'"/>
        <xsl:with-param name="to"><br /></xsl:with-param>
      </xsl:call-template>
    </p>
  </xsl:template>
  
</xsl:stylesheet>
EOT;

$xmldoc = new DOMDocument();
$xmldoc->loadXML($xmlCode);
$xsldoc = new DOMDocument();
$xsldoc->loadXML($xslCode);

$proc = new XSLTProcessor();
$proc->importStyleSheet($xsldoc);
$tmp = $proc->transformToDoc($xmldoc);

#header('content-type: text/plain');
echo $tmp->saveXML($tmp->documentElement);

Output (HTML):

A line break...
...and another one...
...and that's enough.

Output (source):

<p>A line break...<br/>...and another one...<br/>...and that's enough.</p>