Question

J'essaie d'inclure différents fichiers sources (par ex.file1.xml et file2.xml) et résoudre ces inclusions pour une transformation XSLT à l'aide de PHP XSLTProcessor.Voici ma contribution :

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>

transformer.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>

transformer.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"));
?>

Mon résultat souhaité est

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

Ma sortie actuelle est une copie exacte de mon fichier source :

<?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>
Était-ce utile?

La solution

Il s'est avéré que j'avais juste oublié une ligne simple mais importante dans mon code PHP.j'ai dû appeler DOMDocument::xinclude pour que les inclusions soient résolues avant que la transformation ne soit effectuée.

L'exemple complet :

<?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"));
?>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top