PHP XML how to output nice format
You can try to do this:
...// get completed xml document$doc->preserveWhiteSpace = false;$doc->formatOutput = true;$xml_string = $doc->saveXML();echo $xml_string;
You can make set these parameter right after you've created the DOMDocument
as well:
$doc = new DomDocument('1.0');$doc->preserveWhiteSpace = false;$doc->formatOutput = true;
That's probably more concise. Output in both cases is (Demo):
<?xml version="1.0"?><root> <error> <a>eee</a> <b>sd</b> <c>df</c> </error> <error> <a>eee</a> <b>sd</b> <c>df</c> </error> <error> <a>eee</a> <b>sd</b> <c>df</c> </error></root>
I'm not aware how to change the indentation character(s) with DOMDocument
. You could post-process the XML with a line-by-line regular-expression based replacing (e.g. with preg_replace
):
$xml_string = preg_replace('/(?:^|\G) /um', "\t", $xml_string);
Alternatively, there is the tidy extension with tidy_repair_string
which can pretty print XML data as well. It's possible to specify indentation levels with it, however tidy will never output tabs.
tidy_repair_string($xml_string, ['input-xml'=> 1, 'indent' => 1, 'wrap' => 0]);
With a SimpleXml object, you can simply
$domxml = new DOMDocument('1.0');$domxml->preserveWhiteSpace = false;$domxml->formatOutput = true;/* @var $xml SimpleXMLElement */$domxml->loadXML($xml->asXML());$domxml->save($newfile);
$xml
is your simplexml object
So then you simpleXml can be saved as a new file specified by $newfile
<?php$xml = $argv[1];$dom = new DOMDocument();// Initial block (must before load xml string)$dom->preserveWhiteSpace = false;$dom->formatOutput = true;// End initial block$dom->loadXML($xml);$out = $dom->saveXML();print_R($out);