PHP XML Formatting and UTF-8 Output
Generating well-formed XML in PHP is straightforward, but making it readable for human inspection often requires a specific configuration step that many developers overlook. The issue arises because the DOMDocument class defaults to saving output as a single continuous string without indentation or line breaks. When you call $doc->saveXML() directly on a document created with new DomDocument('1.0'), the resulting string will look like <root><error><a>eee</a><b>sd</b><c>df</c></error>...</root> without any whitespace. This is valid XML, but it is difficult to debug and less pleasant to read in a browser or log file.
To transform this dense output into a structured format with tabs or spaces, you must utilize the saveOptions constant. Specifically, you need to enable LIBXML_FORMATTED. You can pass this flag as an argument to the saveXML() method or the save() method depending on whether you are working with a string or a file handle.
Here is how you adjust the code from your snippet to produce indented output:
$doc = new DomDocument('1.0', 'UTF-8');
// create root node
$root = $doc->createElement('root');
$root = $doc->appendChild($root);
$signed_values = array('a' => 'eee', 'b' => 'sd', 'c' => 'df');
// process one row at a time
foreach ($signed_values as $key => $val) {
// add node for each row
$occ = $doc->createElement('error');
$occ = $root->appendChild($occ);
foreach ($signed_values as $fieldname => $fieldvalue) {
$child = $doc->createElement($fieldname);
$child = $occ->appendChild($child);
$value = $doc->createTextNode($fieldvalue);
$value = $child->appendChild($value);
}
}
// Enable formatted output and save as UTF-8
echo $doc->saveXML(LIBXML_FORMATTED | LIBXML_NOEMPTYTAG);
There are two critical changes here. First, the constructor new DomDocument('1.0', 'UTF-8') explicitly sets the internal encoding to UTF-8. While modern PHP defaults often handle this gracefully, specifying it ensures that special characters and non-ASCII text are handled correctly from the moment of creation. If you omit the second argument, the default encoding might be ISO-8859-1 (Latin-1) in older PHP versions or specific configurations, which could lead to mojibake if your data contains accented characters.
Second, and most importantly, passing LIBXML_FORMATTED as the second argument to saveXML() tells the DOM parser to insert newlines after tags and indent child elements using spaces or tabs. The amount of indentation is controlled by the LIBXML_HTML_FILE_SAVE_FILE option in some contexts, but for standard XML saving, the library uses a default number of spaces per level (typically 4).
You might also notice the addition of LIBXML_NOEMPTYTAG in the example above. In your original data structure, every element has text content, so this flag isn't strictly necessary yet. However, it is good practice to include it when formatting XML because it prevents the output of empty tags like <br /> or <img> which can clutter the visual representation if you ever switch to generating HTML within the XML.
Another common pitfall involves the order of arguments in saveXML. In PHP 5.3 and earlier, the signature was different, accepting options as a string or integer flags differently than modern versions. Ensure your version of PHP supports passing an integer bitmask for formatting options, which is standard in PHP 7 and 8. If you are using a framework like Laravel, you might find that helper classes abstract this away, but understanding the underlying DOMDocument behavior ensures you can handle edge cases where built-in helpers fail.
By combining the explicit UTF-8 declaration with the LIBXML_FORMATTED flag, you achieve both strict character encoding compliance and a human-readable structure. This approach is essential when generating XML reports that need to be opened directly in text editors or viewed clearly within browser developer tools.
