简体   繁体   中英

How can I display XML with whitespace formatting?

I have a web page that builds an XML from an existing XML applying changes. I want to output the new XML file in a textarea as a preview. It displays any nodes that were present in the original XML with the proper whitespaces/formatting (indents and linebreaks) that the original XML had just fine, but any new nodes are all displayed on one line with no indents. Example:

<original parent node>
    <original child>value</original child>
</original parent node>
<original parent node>
    <new child>value</new child><new child>value</new child><new child>value</new child><new child>value</new child><new child>value</new child><new child>value</new child>
</original parent node>

Here is the code that writes and reads back in the XML:

$dom = new DOMDocument('1.0');
$dom->preserveWhiteSpace = true;
$dom->formatOutput = true;
$dom->loadXML($xml->asXML());
file_put_contents($file, $dom->saveXML());
echo "<textarea cols='100' rows='40'>".file_get_contents($file)."</textarea>";

I'm also using SimpleXML to manipulate the XMLS. How can I get the proper whitespacing to display for the new nodes?

I've found that formatOutput only works when preserveWhiteSpace is disabled:

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

Add this, it works for me.

echo '<script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>';
echo "<br/> <pre class=\"prettyprint\" >". htmlentities($dom->saveXML($dom->firstChild->firstChild->firstChild))."</pre>"; 

You can delete $dom->firstChild->firstChild->firstChild for more info.

尝试:

echo "<textarea cols='100' rows='40'>".htmlspecialchars($xml->asXML())."</textarea>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM