Question

I am trying to include different source files (e.g. file1.xml and file2.xml) and have these includes resolved for an XSLT transformation using PHPs XSLTProcessor. This is my input:

source.xml

<?xml version="1.0" encoding="utf-8" ?>
<root xmlns:xi="http://www.w3.org/2001/XInclude">
    <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="file1.xml" />
    <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="file2.xml" />
</root>

transform.xsl

<?xml version="1.0" encoding="UTF-8"?>
<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xi="http://www.w3.org/2001/XInclude">
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>
</xsl:transform>

transform.php

<?php
function transform($xml, $xsl) {
    global $debug;

    // XSLT Stylesheet laden
    $xslDom = new DOMDocument("1.0", "utf-8");
    $xslDom->load($xsl, LIBXML_XINCLUDE);

    // XML laden
    $xmlDom = new DOMDocument("1.0", "utf-8");
    $xmlDom->loadHTML($xml);                // loadHTML to handle possibly defective markup

    $xsl = new XsltProcessor();             // create XSLT processor
    $xsl->importStylesheet($xslDom);        // load stylesheet
    return $xsl->transformToXML($xmlDom);   // transformation returns XML
}
exit(transform("source.xml", "transform.xsl"));
?>

My desired output is

<?xml version="1.0" encoding="utf-8" ?>
<root>
    <!-- transformed contents of file1.xml -->
    <!-- transformed contents of file2.xml -->
</root>

My current output is an exact copy of my source file:

<?xml version="1.0" encoding="utf-8" ?>
<root>
    <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="file1.xml" />
    <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="file2.xml" />
</root>
Was it helpful?

Solution

It turned out, I just forgot one simple but important line in my PHP code. I had to call DOMDocument::xinclude to have the includes resolved before the transformation is done.

The full example:

<?php
function transform($xml, $xsl) {
    global $debug;

    // XSLT Stylesheet laden
    $xslDom = new DOMDocument("1.0", "utf-8");
    $xslDom->load($xsl, LIBXML_XINCLUDE);

    // XML laden
    $xmlDom = new DOMDocument("1.0", "utf-8");
    $xmlDom->load($xml);

    $xmlDom->xinclude();                    // IMPORTANT!

    $xsl = new XsltProcessor();
    $xsl->importStylesheet($xslDom);
    return $xsl->transformToXML($xmlDom);
}
exit(transform("source.xml", "transform.xsl"));
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top