Unfortunately PHP's DOM extension doesn't support use of:
<?xml-stylesheet type="text/xsl" ... ?>
processing instruction.
Here is an example, how to implement it using XPath query and extending DOMDocument by a method output().
<?php
// This simple function adds missing direct usage of anonymous instances
// in PHP5's reference model
function a($var) {
return $var;
}
// Extended DOMDocument class
class MyDOMDocument extends DOMDocument
{
public function output()
{
$stylesheets = array();
$PIs = a(new DOMXPath($this))
->query('/processing-instruction("xml-stylesheet")');
foreach($PIs as $PI)
{
// This might be implemented cleaner by regular parsing
// of DOMProcessingInstruction::data property
if(ereg('type *= *"text/xsl" +href *= *"([^"]+)"', $PI->data, $mem))
{
// Here should be verified, that XSL file exists.
a($stylesheets[] = new DOMDocument())->load($mem[1]);
}
}
if($stylesheets)
{
$processor = new XSLTProcessor();
foreach($stylesheets as $stylesheet)
$processor->importStylesheet($stylesheet);
return $processor->transformToDoc($this);
}
// If no stylesheet instructions present, return self directly
else return $this;
}
}
?>
Usage:
<?php
$document = new MyDOMDocument();
$document->load('my.xml');
echo $document->output()->saveXML();
?>
With following file my.xml:
<?xml version="1.0" ?>
<?xml-stylesheet type="text/xsl" href="my.xsl" ?>
<my-root />
and existing file my.xsl that code will transform the xml file using my.xsl and output the result.
