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?
This is a slight variation of the above theme but I'm putting here in case others hit this and cannot make sense of it ...as I did.
When using saveXML(), preserveWhiteSpace in the target DOMdocument does not apply to imported nodes (as at PHP 5.6).
Consider the following code:
In this context, the
$dom->saveXML();
statement will NOT pretty print the content imported from $message, but content originally in $dom will be pretty printed.In order to achieve pretty printing for the entire $dom document, the line:
must be included after the
$message = new DOMDocument();
line - ie. the document/s from which the nodes are imported must also have preserveWhiteSpace = false.With a SimpleXml object, you can simply
$xml
is your simplexml objectSo then you simpleXml can be saved as a new file specified by
$newfile
Two different issues here:
Set the formatOutput and preserveWhiteSpace attributes to
TRUE
to generate formatted XML:Many web browsers (namely Internet Explorer and Firefox) format XML when they display it. Use either the View Source feature or a regular text editor to inspect the output.
See also xmlEncoding and encoding.
Tried all the answers but none worked. Maybe it's because I'm appending and removing childs before saving the XML. After a lot of googling found this comment in the php documentation. I only had to reload the resulting XML to make it work.