• PHP Video Tutorials

PHP - XSLTProcessor::transformToXml() Function



Definition and Usage

XML is a mark-up language to share the data across the web, XML is for both human read-able and machine read-able. XSL extension is an implementation of thw XSL standard to perform XSTL transformation using the libxslt library.

The XSLTProcessor::transformToXml() function accepts an object of the class DOMNode as a parameter and transforms it to a string by applying a style sheet to it.

Syntax

XSLTProcessor::transformToXml($doc);

Parameters

Sr.No Parameter & Description
1

doc(Mandatory)

This is an object of the DOMNode class representing the document that is to be transformed.

Return Values

This function returns a string value representing the result of the transformation in case of success and a boolean value which is FALSE incase of failure.

PHP Version

This function was first introduced in PHP Version 5 and works in all the later versions.

Example

Following is an example of this function −

sample.xml:

<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="example.xsl"?>
<Tutorial>
   <Title>JavaFX</Title>
   <Authors>
      <Author>Krishna</Author>
      <Author>Rajeev</Author>
   </Authors>
   <Body>Sample text</Body>
</Tutorial>

sample.xsl:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="text"/>

   <xsl:template match="/">
      Title - <xsl:value-of select="/Tutorial/Title"/>
      Authors: <xsl:apply-templates select="/Tutorial/Authors/Author"/>
   </xsl:template>

   <xsl:template match="Author">
      - <xsl:value-of select="." />
   </xsl:template>
</xsl:stylesheet>

sample.php:

<?php
   //Loading an XSL document
   $xsl = new DOMDocument();
   $xsl->load("sample.xsl");

   //Loading an XML document
   $xml = new DOMDocument();
   $xml->load("sample.xml");

   //Creating an XSLTProcessor
   $proc = new XSLTProcessor();

   //Importing the XSL document
   $proc->importStyleSheet($xsl);

   //Transforming the style to XML
   $res = $proc->transformToXml($xml);
   print($res);
?>

This will produce following result −

Title - JavaFX
   Authors:
   - Krishna
   - Rajeev
php_function_reference.htm
Advertisements