Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : XSL functions

XSL functions

Introduction

The XSL extension implements the XSL standard, performing » XSLT transformations using the » libxslt library

Requirements

This extension uses libxslt which can be found at » http://xmlsoft.org/XSLT/. libxslt version 1.1.0 or greater is required.

Installation

PHP 5 includes the XSL extension by default and can be enabled by adding the argument --with-xsl[=DIR] to your configure line. DIR is the libxslt installation directory.

Predefined Classes

XSLTProcessor

Constructor

Methods

Examples

Many examples in this reference require both an XML and an XSL file. We will use collection.xml and collection.xsl that contains the following:

Example 2648. collection.xml

<collection>
<cd>
 <title>Fight for your mind</title>
 <artist>Ben Harper</artist>
 <year>1995</year>
</cd>
<cd>
 <title>Electric Ladyland</title>
 <artist>Jimi Hendrix</artist>
 <year>1997</year>
</cd>
</collection>


Example 2649. collection.xsl

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="owner" select="'Nicolas Eliaszewicz'"/>
<xsl:output method="html" encoding="iso-8859-1" indent="no"/>
<xsl:template match="collection">
 Hey! Welcome to <xsl:value-of select="$owner"/>'s sweet CD collection!
 <xsl:apply-templates/>
</xsl:template>
<xsl:template match="cd">
 <h1><xsl:value-of select="title"/></h1>
 <h2>by <xsl:value-of select="artist"/> - <xsl:value-of select="year"/></h2>
 <hr />
</xsl:template>
</xsl:stylesheet>


Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

XSL_CLONE_AUTO (integer)
XSL_CLONE_NEVER (integer)
XSL_CLONE_ALWAYS (integer)
LIBXSLT_VERSION (integer)
libxslt version like 10117. Available as of PHP 5.1.2.
LIBXSLT_DOTTED_VERSION (string)
libxslt version like 1.1.17. Available as of PHP 5.1.2.
LIBEXSLT_VERSION (integer)
libexslt version like 813. Available as of PHP 5.1.2.
LIBEXSLT_DOTTED_VERSION (string)
libexslt version like 1.1.17. Available as of PHP 5.1.2.

Table of Contents

XSLTProcessor::__construct — Creates a new XSLTProcessor object
XSLTProcessor::getParameter — Get value of a parameter
XSLTProcessor::hasExsltSupport — Determine if PHP has EXSLT support
XSLTProcessor::importStylesheet — Import stylesheet
XSLTProcessor::registerPHPFunctions — Enables the ability to use PHP functions as XSLT functions
XSLTProcessor::removeParameter — Remove parameter
XSLTProcessor::setParameter — Set value for a parameter
XSLTProcessor::transformToDoc — Transform to a DOMDocument
XSLTProcessor::transformToURI — Transform to URI
XSLTProcessor::transformToXML — Transform to XML

Code Examples / Notes » ref.xsl

mnot

You can set an HTTP proxy for the XSLT document() function to use (as well as DTD external references) by setting http_proxy in the environment.
E.g., in Apache configuration;
SetEnv http_proxy http://127.0.0.1:3128/


kekoajs

Wow, I spent the better part of a day looking for how one could pass an entire test expression to an XSL stylesheet.  It seems that the XSLT 1.0 specification doesn't support it but PHP 5 (and maybe 4s) inclusion of  EXSLT allows one to do exactly that...
simply add these lines...
xmlns:dyn="http://exslt.org/dynamic"
extension-element-prefixes="dyn"
to the <xsl:stylesheet> element and when using an expression stored in a <xsl:param> element write
<xsl:if test="dyn:evaluate($param-name)">
and viola!  you can now use expressions generated externally in your stylesheet!
EXSLT adds many useful functions that can be integrated into your XSL in a similar fashion.  You can go to http://exslt.org/ to learn more...


jw

The following code is a wrapper to support calls to some of the old xslt_* functions:
<?
if (PHP_VERSION >= 5) {
// Emulate the old xslt library functions
function xslt_create() {
return new XsltProcessor();
}
function xslt_process($xsltproc,
                         $xml_arg,
                         $xsl_arg,
                         $xslcontainer = null,
                         $args = null,
                         $params = null) {
// Start with preparing the arguments
$xml_arg = str_replace('arg:', '', $xml_arg);
$xsl_arg = str_replace('arg:', '', $xsl_arg);
// Create instances of the DomDocument class
$xml = new DomDocument;
$xsl = new DomDocument;
// Load the xml document and the xsl template
$xml->loadXML($args[$xml_arg]);
$xsl->loadXML($args[$xsl_arg]);
// Load the xsl template
$xsltproc->importStyleSheet($xsl);
// Set parameters when defined
if ($params) {
foreach ($params as $param => $value) {
$xsltproc->setParameter("", $param, $value);
}
}
// Start the transformation
$processed = $xsltproc->transformToXML($xml);
// Put the result in a file when specified
if ($xslcontainer) {
return @file_put_contents($xslcontainer, $processed);
} else {
return $processed;
}
}
function xslt_free($xsltproc) {
unset($xsltproc);
}
}
$arguments = array(
'/_xml' => file_get_contents("newxslt.xml"),
'/_xsl' => file_get_contents("newxslt.xslt")
);
$xsltproc = xslt_create();
$html = xslt_process(
   $xsltproc,
   'arg:/_xml',
   'arg:/_xsl',
   null,
   $arguments
);
xslt_free($xsltproc);
print $html;
?>


ryan d. hatch

Looking for php_xsl.dll?
If you installed on Windows using the MSI Installer - you may not have it.
1.) Add/Remove Programs and Change PHP Installation.  Select XSL Extension.
OR
2.) Download complete .zip file of PHP and you can copy php_xsl.dll into your PHP/etc directory.
Just a note.
Ryan D. Hatch


fabrice bonny

In response to how to use entities from DTD (internal or external) in XSLT. It works if you do this way:
$xsl = new DOMDocument;
$xsl->resolveExternals = TRUE;
$xsl->substituteEntities = TRUE;
$xsl->load(...);
Hope this helps! ;-)


17-mar-2006 05:14

In response to appletalk at gmail dot com
<snip>
As many of you may have noticed, DOM parser gives errors if the '&nbsp;' entity is present. The E_WARN message looks like:
Warning: DOMDocument::load() [function.load]: Entity 'nbsp' not defined in ...
There're many ways to solve this:
.....
b) Defining &nbsp;
At the top of the document, after the <?xml?> definition, add:
  <!DOCTYPE xsl:stylesheet [
  <!ENTITY nbsp "&#160;" >
  ]>
.......</snip>
Just wanted to let people know that option b does NOT work. I'm not sure why this isn't implemented correctly, but it isn't, so don't waste your time. It's unfortunate the DOMXSL transform is so much less capable than the old xslt function.


rojaro

If you're want to use XML from a variable e.g. $xmldata but the XSLT-StyleSheet from a file, you can do it also the following way:
<?php
$xslt = new xsltProcessor;
$xslt->importStyleSheet(DomDocument::load('filename.xsl'));
print $xslt->transformToXML(DomDocument::loadXML($xmldata));
?>


adrian

If you want to use the document()-function inside your XSL stylesheet, please note that you have to use an absolute path there.
Important for windows users: the absolute path *has* to be with forward slashes, so subsitute windows-path-backslashes to forward slashes before you transform the document.
Examples:
This will NOT work:
<xsl:copy-of select="document('test.xml')" />
This will also NOT work:
<xsl:copy-of select="document('c:\temp\test.xml')" />
But this WILL work:
<xsl:copy-of select="document('c:/temp/test.xml')" />


olivier dot sow

if you have 'XML parser error 4: not well-formed (invalid token)' error without but your are sure to do no error at all, try this:
<?
function
XSL_transformation($XMLFile,$XSLFile,$ResultFile,$xsl_params){

$Str = '';
$xp = xslt_create() or trigger_error('Could not create XSLT process.', E_USER_ERROR);
xslt_set_encoding($xp, 'ISO-8859-1');
// read the files into memory
$xsl_string = join('', file($XSLFile));
$xml_string = join('', file($XMLFile));
// set the argument buffer
$arg_buffer = array('/xml' => $xml_string, '/xsl' => $xsl_string);
// process the two files to get the desired output
if (($Str = xslt_process($xp, 'arg:/xml', 'arg:/xsl', NULL, $arg_buffer, $xsl_params))){
//Saves transformation result into '$ResultFile'
$fp = fopen($ResultFile,"w+");
fwrite($fp,$Str);
fclose($fp);

return true;
}

return false;
}
?>
found here: http://bugs.php.net/bug.php?id=16193


rd

If you get the following warning message:
xsltApplyOneTemplate: _if_ was not compiled in (if can for example be apply-template or some other method), i've found that the problem seems to be an &nbsp; directly before the <xsl:if> or what ever is causing the problem.
One way to get thru the problem is to use span tags around &nbsp;  like : <span>&nbsp;</span>


venkatesh

Here is function to read from the XSL sheet which is saved as a text file.
function ReadExcelSheet($filename){
            $test=file($filename);
            $ar1=str_replace("~[^\t]*\t","\t",$test);
            $ar2=str_replace("~","",$ar1);
            $ar=str_replace("³","",$ar2);
            $temp=array();
            for ($i=0; $i<count($ar); $i++) {
                      if((substr($ar[$i],0,1)!= "\t")){
                          if($ar[$i]!=="\r\n"){
                          array_push($temp,$ar[$i]);
           }
       }
   }
   $name=split("\t",$temp[0]);
   $ExcelList=array();
   for($i=1;$i<count($temp);$i++){
    $split_result=split("\t",$temp[$i]);
    array_push($ExcelList,$split_result);
   }
   $result=insert_into_array($ExcelList,0,$name);
   return($result);
}


geoffreyj dot lee

Here are a couple useful tips for those who care about cross-browser compatibility.
Given:
<script type="text/javascript" src="test.js"></script>
XSLT will automatically condense it to:
<script type="text/javascript" src="test.js"/>
While this is good, Internet Explorer breaks on empty script tags. So, the simple solution is to add something to prevent an empty tag. For example:
<script type="text/javascript" src="test.js"><xsl:comment/></script>
Produces:
<script type="text/javascript" src="test.js">
</script>
------------------------
Also, here is a way to use IE's conditional comments:
<xsl:comment>[if gte IE 5]&#62;
&#60;link rel="stylesheet" type="text/css" href="ie.css" /&#62;
&#60;![endif]</xsl:comment>
Produces:
<!--[if gte IE 5]>
<link rel="stylesheet" type="text/css" href="ie.css" />
<![endif]-->
This will let you isolate IE-related CSS without needing to use ugly CSS hacks.


28-apr-2006 02:26

Enable libxslt library, PHP 5, under windows:
To Enable:
In your php.ini
1. Uncomment ;extension=php_xsl.dll
2. Change extension_dir to
    extension_dir = "./ext"
To Confirm:
1. In a test.php page:
<?php phpinfo() ?>
2. Run test.php
3. Search for "libxslt Version". It should return a version number in a XSL headed table.
Further info Google
"Configuring and Testing PHP Servers for XSL Support"


gabriel dot birke

Each <xsl:message> tag will generate a PHP error (level Warning). If you want to collect and pretty-print them, you could use a custom error handling function that collects the warnings in a static variable.

pb

Calling the Saxon XSLT Processor is a very esay task to do!
You just need to do some simple task
1. Install the JavaBridge for PHP
2. Download the freeware (B) Saxon distribution from http://saxon.sourceforge.net/
3. Put the jar files in a directory whre you have access
4. Use this sample of code
// Directory where the jar files are located
define("SAXON_DIR", $_SERVER['DOCUMENT_ROOT']."/saxonb8.9.0/");
// include the jars
java_require(SAXON_DIR."saxon8.jar;".SAXON_DIR."saxon8-dom.jar");


$sXslFile = $_SERVER['DOCUMENT_ROOT']."/myfirst.xsl"; // The xsl file
$sXmlFile = $_SERVER['DOCUMENT_ROOT']."/myfirst.xml"; // The xml file
try
{
 $oXslSource = new java("javax.xml.transform.stream.StreamSource", "file://".$sXslFile);
 $oXmlSource = new java("javax.xml.transform.stream.StreamSource", "file://".$sXmlFile);
 $oFeatureKeys = new JavaClass("net.sf.saxon.FeatureKeys");
 // Create the Factory
 $oTransformerFactory = new java("net.sf.saxon.TransformerFactoryImpl");
 //Disable source document validation
 $oTransformerFactory->setAttribute($oFeatureKeys->SCHEMA_VALIDATION, 4);
 // Create a new Transformer
 $oTransFormer = $oTransformerFactory->newTransformer($oXslSource);
   
 // Create a StreamResult to store the output
 $oResultStringWriter = new java("java.io.StringWriter");
 $oResultStream = new java("javax.xml.transform.stream.StreamResult", $oResultStringWriter);
 
 // Transform
 $oTransFormer->transform($oXmlSource, $oResultStream);
 
 // Echo the output from the transformation
 echo java_cast($oResultStringWriter->toString(), "string");
 
}
catch(JavaException $e){
  echo java_cast($e->getCause()->toString(), "string");
  exit;
}
5. Enjoy
This is working quite well.


appletalk

As many of you may have noticed, DOM parser gives errors if the '&nbsp;' entity is present. The E_WARN message looks like:
Warning: DOMDocument::load() [function.load]: Entity 'nbsp' not defined in ...
There're many ways to solve this:
a) The hard way
<xsl:text disable-output-escaping="yes"> &amp;nbsp;</xsl:text>
b) Defining &nbsp;
At the top of the document, after the <?xml?> definition, add:
  <!DOCTYPE xsl:stylesheet [
   <!ENTITY nbsp "&#160;" >
   ]>
c) External Doctype
Just in case you want need other HTML entities, you can call an external doctype with the proper definitions
<!DOCTYPE page SYSTEM "http://gv.ca/dtd/character-entities.dtd">
Of course, you can download the file and place it in your server.


basslines

As far as I can tell, the most recent stable versions of LibXML/LibXSLT/LibEXSLT do NOT support xPath 2.0 / XSLT 2.0 transformations. The only support for XSLT 2.0 that I've found is in Java's SAXON processor (http://saxon.sourceforge.net/).

vasil rangelov

@basslines at gmail dot com
"
As far as I can tell, the most recent stable versions of LibXML/LibXSLT/LibEXSLT do NOT support xPath 2.0 / XSLT 2.0 transformations. The only support for XSLT 2.0 that I've found is in Java's SAXON processor (http://saxon.sourceforge.net/).
"
Using SAXON or AltovaXML by using their JAVA bindings could prove to be a difficult task to do, and .NET seems to be buggy (at least for me). However, I've made a class that uses SAXON or AltovaXML from the command line. AltovaXML could also be used with COM, provided it's registered as a COM component.
You can download my wrapper from:
http://xslt2processor.sourceforge.net/
I still need to implement a more graceful error handling (the way the XSL extension uses the Libxml functions), and once the bug
http://bugs.php.net/bug.php?id=41577
is fixed, I'll implement the .NET interfaces too.
I'll appreciate any feedback.


Change Language


Follow Navioo On Twitter
.NET Functions
Apache-specific Functions
Alternative PHP Cache
Advanced PHP debugger
Array Functions
Aspell functions [deprecated]
BBCode Functions
BCMath Arbitrary Precision Mathematics Functions
PHP bytecode Compiler
Bzip2 Compression Functions
Calendar Functions
CCVS API Functions [deprecated]
Class/Object Functions
Classkit Functions
ClibPDF Functions [deprecated]
COM and .Net (Windows)
Crack Functions
Character Type Functions
CURL
Cybercash Payment Functions
Credit Mutuel CyberMUT functions
Cyrus IMAP administration Functions
Date and Time Functions
DB++ Functions
Database (dbm-style) Abstraction Layer Functions
dBase Functions
DBM Functions [deprecated]
dbx Functions
Direct IO Functions
Directory Functions
DOM Functions
DOM XML Functions
enchant Functions
Error Handling and Logging Functions
Exif Functions
Expect Functions
File Alteration Monitor Functions
Forms Data Format Functions
Fileinfo Functions
filePro Functions
Filesystem Functions
Filter Functions
Firebird/InterBase Functions
Firebird/Interbase Functions (PDO_FIREBIRD)
FriBiDi Functions
FrontBase Functions
FTP Functions
Function Handling Functions
GeoIP Functions
Gettext Functions
GMP Functions
gnupg Functions
Net_Gopher
Haru PDF Functions
hash Functions
HTTP
Hyperwave Functions
Hyperwave API Functions
i18n Functions
IBM Functions (PDO_IBM)
IBM DB2
iconv Functions
ID3 Functions
IIS Administration Functions
Image Functions
Imagick Image Library
IMAP
Informix Functions
Informix Functions (PDO_INFORMIX)
Ingres II Functions
IRC Gateway Functions
PHP / Java Integration
JSON Functions
KADM5
LDAP Functions
libxml Functions
Lotus Notes Functions
LZF Functions
Mail Functions
Mailparse Functions
Mathematical Functions
MaxDB PHP Extension
MCAL Functions
Mcrypt Encryption Functions
MCVE (Monetra) Payment Functions
Memcache Functions
Mhash Functions
Mimetype Functions
Ming functions for Flash
Miscellaneous Functions
mnoGoSearch Functions
Microsoft SQL Server Functions
Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
Mohawk Software Session Handler Functions
mSQL Functions
Multibyte String Functions
muscat Functions
MySQL Functions
MySQL Functions (PDO_MYSQL)
MySQL Improved Extension
Ncurses Terminal Screen Control Functions
Network Functions
Newt Functions
NSAPI-specific Functions
Object Aggregation/Composition Functions
Object property and method call overloading
Oracle Functions
ODBC Functions (Unified)
ODBC and DB2 Functions (PDO_ODBC)
oggvorbis
OpenAL Audio Bindings
OpenSSL Functions
Oracle Functions [deprecated]
Oracle Functions (PDO_OCI)
Output Control Functions
Ovrimos SQL Functions
Paradox File Access
Parsekit Functions
Process Control Functions
Regular Expression Functions (Perl-Compatible)
PDF Functions
PDO Functions
Phar archive stream and classes
PHP Options&Information
POSIX Functions
Regular Expression Functions (POSIX Extended)
PostgreSQL Functions
PostgreSQL Functions (PDO_PGSQL)
Printer Functions
Program Execution Functions
PostScript document creation
Pspell Functions
qtdom Functions
Radius
Rar Functions
GNU Readline
GNU Recode Functions
RPM Header Reading Functions
runkit Functions
SAM - Simple Asynchronous Messaging
Satellite CORBA client extension [deprecated]
SCA Functions
SDO Functions
SDO XML Data Access Service Functions
SDO Relational Data Access Service Functions
Semaphore
SESAM Database Functions
PostgreSQL Session Save Handler
Session Handling Functions
Shared Memory Functions
SimpleXML functions
SNMP Functions
SOAP Functions
Socket Functions
Standard PHP Library (SPL) Functions
SQLite Functions
SQLite Functions (PDO_SQLITE)
Secure Shell2 Functions
Statistics Functions
Stream Functions
String Functions
Subversion Functions
Shockwave Flash Functions
Swish Functions
Sybase Functions
TCP Wrappers Functions
Tidy Functions
Tokenizer Functions
Unicode Functions
URL Functions
Variable Handling Functions
Verisign Payflow Pro Functions
vpopmail Functions
W32api Functions
WDDX Functions
win32ps Functions
win32service Functions
xattr Functions
xdiff Functions
XML Parser Functions
XML-RPC Functions
XMLReader functions
XMLWriter Functions
XSL functions
XSLT Functions
YAZ Functions
YP/NIS Functions
Zip File Functions
Zlib Compression Functions
eXTReMe Tracker