Here are the codes:
$doc = new DomDocument('1.0');
// 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);
// add a child node for each field
foreach ($signed_values as $fieldname => $fieldvalue) {
$child = $doc->createElement($fieldname);
$child = $occ->appendChild($child);
$value = $doc->createTextNode($fieldvalue);
$value = $child->appendChild($value);
}
}
// get completed xml document
$xml_string = $doc->saveXML() ;
echo $xml_string;
If I print it in the browser I don't get nice XML structure like
<xml> n tab <child> etc.
I just get
<xml><child>ee</child></xml>
And I want to be utf-8 How is this all possible to do?
You can try to do this:
You can make set these parameter right after you've created the
DOMDocument
as well:That's probably more concise. Output in both cases is (Demo):
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. withpreg_replace
):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.