Call user defined functions from XSL

function replace_email($nodes) {
    return preg_replace('/([^@\s]+)@([-a-z0-9]+\.)+[a-z]{2,}/is',
                        '$1@...',
                        $nodes[0]->nodeValue);
}
 
$dom  = new DOMDocument;
$dom->load('addresses.xml');
$xsl  = new DOMDocument
$xsl->load('stylesheet.xsl');
 
$xslt = new XSLTProcessor();
$xslt->importStylesheet($xsl);
$xslt->registerPhpFunctions();
print $xslt->transformToXML($dom);

Stylesheet.xsl

<?xml version="1.0" ?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:php="http://php.net/xsl"
  xsl:extension-element-prefixes="php">
 
<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>
 
 
<xsl:template match="/addresses/person/email">
  <xsl:copy>
    <xsl:value-of select="php:function('replace_email', node())" />
  </xsl:copy>
</xsl:template>
</xsl:stylesheet>

Input XML:

<?xml version="1.0"?>
<addresses>
    <person>
        <name>Ramesh babu</name>
	<firstname>Ramesh</firstname>
	<lastname>babu</lastname>
        <email>Ram@w3mauthor.com</email>
    </person>
    <person>
        <name>Jolld babu</name>
	<firstname>jolld</firstname>
	<lastname>babu</lastname>
        <email>Jolld@w3mauthor</email>
    </person>
</addresses>

Share Article/Example:
  • DotNetKicks
  • DZone
  • StumbleUpon
  • Print
  • Add to favorites
  • Digg
  • del.icio.us
  • Twitter
  • Facebook
  • LinkedIn
  • Posterous
  • Slashdot

Filed Under: PHP XML Examples

RSSComments (0)

Trackback URL

Leave a Reply




If you want a picture to show with your comment, go get a Gravatar.