Search code examples
phpxmlxsltdomdocument

Domdocument: Why XSLT Transformation Output became single line?


Hi I wanted to know how to retail the xml structure when using XSLT,

I have these code below,

        /* XSLT File */
        $xsl = new \DOMDocument;
        $xsl->loadXML($xsltData[0]->xslt_template);
        $xsl->preserveWhiteSpace = false;
        $xsl->formatOutput = true;
        /* Combine and Transform XML and XSLT */
        $proc = new \XSLTProcessor;
        $proc->importStyleSheet($xsl); 
        $proc->preserveWhiteSpace = false;
        $proc->formatOutput = true;
        $transformedOutPut = $proc->transformToXML($xml);

Here is my input xml

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
  <cd>
    <titleA style="test" size="123">Kevin del </titleA>
    <address>1119 Johnson Street, San Diego, California</address>
    <country>USA</country>
    <company>Columbia</company>
    <price>10.90</price>
    <year>1985</year>
  </cd>
</catalog>

and here is my XSLT from the database with preserve spacing,

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <catalognew>
    <container-title>My Data</container-title>
    <xsl:for-each select="catalog/cd">
    <cdnew>
      <titlenew><xsl:value-of select="titleA"/></titlenew>
      <addressnew>
        <street><xsl:value-of select="address/street"/></street>
        <city><xsl:value-of select="address/city"/></city>
        <state><xsl:value-of select="address/state"/></state>
      </addressnew>
    </cdnew>
    </xsl:for-each>
  </catalognew>
</xsl:template>
</xsl:stylesheet>

Why doe it give me a single line result and not retaining its original structure,

<?xml version="1.0"?>
<catalognew><container-title>My Data</container-title><cdnew><titlenew>Kevin del </titlenew><addressnew><street>1119 JOHNSON STREET</street><city>SAN DIEGO</city><state>CALIFORNIA</state></addressnew></cdnew></catalognew>

I hope someone can help me,

Thank You,


Solution

  • The problem seems to be that you need to ensure the final document object has the settings to format the output. So rather than use transformToXML($xml), this creates a new document and ensures that this new document has the formatting options set before outputting the result...

    $transformedOutPut = $proc->transformToDoc($xml);
    $transformedOutPut->preserveWhiteSpace = true;
    $transformedOutPut->formatOutput = true;
    
    print_r($transformedOutPut->saveXML());
    

    gives...

    <?xml version="1.0"?>
    <catalognew>
      <container-title>My Data</container-title>
      <cdnew>
        <titlenew>Kevin del </titlenew>
        <addressnew>
          <street/>
          <city/>
          <state/>
        </addressnew>
      </cdnew>
    </catalognew>