Transform XML with XSLT in PHP

前端 未结 1 711
离开以前
离开以前 2020-12-10 13:45

I\'m trying to combine two xml-files and with a XSLT-file transform them into a XHTML-page. I have not done this before and can´t figure out how to do it. This is what I hav

相关标签:
1条回答
  • 2020-12-10 14:36

    This might be an answer to part of your question.

    With regard to using two XML files, you have a couple of options. You could combine the two XML files into one larger one, then apply a transform to that. Alternatively, you could use the XSLT document() function to load one of the XML files from within an XSLT.

    1. Make one large XML document

    <?php
    
    // XML
    $x1 = file_get_contents("file1.xml");
    $x2 = file_get_contents("file2.xml");
    $xml_doc = new DOMDocument();
    $xml_doc->loadXML("<root><x1>$x1</x1><x2>$x2</x2></root>");
    
    // XSL
    $xsl_doc = new DOMDocument();
    $xsl_doc->load("file.xsl");
    
    // Proc
    $proc = new XSLTProcessor();
    $proc->importStylesheet($xsl_doc);
    $newdom = $proc->transformToDoc($xml_doc);
    
    print $newdom->saveXML();
    
    ?>
    

    2. Use the XSTL document() function

    <?php
    
    // XML
    $xml_doc = new DOMDocument();
    $xml_doc->load("file1.xml");
    
    
    // XSL
    $xsl_doc = new DOMDocument();
    $xsl_doc->load("file.xsl");
    
    // Proc
    $proc = new XSLTProcessor();
    $proc->importStylesheet($xsl_doc);
    $newdom = $proc->transformToDoc($xml_doc);
    
    print $newdom->saveXML();
    
    ?>
    
    
    <?xml version="1.0" encoding="utf-8"?>
    <xsl:stylesheet version="1.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    
      <xsl:variable name="file2" select="document('file2.xml')/*"/>
    
      <xsl:template match="/">
        <xsl:copy-of select="$file2"/>
      </xsl:template>
    
    </xsl:transform>
    

    I tend to use the first technique more than the second. I don't like hardcoding filenames into XSLT templates. When I do use the second method, I would usually pass in the filename as an external parameter to avoid having it hardcoded in the XSLT.

    0 讨论(0)
提交回复
热议问题