Search code examples
phphtmlalignmentpre

PHP code to align XML content in a `pre` tag


I want to align the XML syntax displayed in a pre tag on a web page.

As showed here, we have plenty of solution to highlight the syntax but not align them i.e. adding a number of preceeding spacings for the code block.

If you know how, please show me.

The original XML text:

<abb><ccc></ccc><ccc><edd></edd></ccc></abb>

After aligned, it should be:

<abb>
    <ccc>
    </ccc>
    <ccc>
        <edd>
        </edd>
    </ccc>
</abb>

Solution

  • You can use the DOMDocument class to format the XML:

    $dom = new DOMDocument;
    $dom->preserveWhiteSpace = false;
    $dom->loadXML($youtXMLString); 
    $dom->formatOutput = true;
    echo $dom->saveXml();