note 75945 deleted from simplexmlelement.asXML by danbrown
| From: | danbrown@php.net | Date: | Fri, 28 Jan 2011 14:32:55 +0000 |
| Subject: | note 75945 deleted from simplexmlelement.asXML by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-176443@lists.php.net to get a copy of this message | ||
Note Submitter: Fred Trotter
----
When trying to use the DOMDocument method for pretty printing the output of asXML be careful how you
format the starting XML string. It cannot have spaces or other hidden chars "\n". I also
had trouble with using different types of quotes for the starting XML, but I am unable to replicate
that. So if you cannot get this to work then you might try swapping the single and double quotes.
<?php
$no_spaces = '<?xml version="1.0"
encoding="UTF-8"?><Example></Example>';
$one_space = '<?xml version="1.0" encoding="UTF-8"?><Example>
</Example>';
echo printy($no_spaces);
/* Outputs
<?xml version="1.0"?>
<Example>
<poop from="Myself">
<smell>stinky</smell>
</poop>
</Example>
*/
echo printy($one_space);
/* Outputs... note the space...
<?xml version="1.0"?>
<Example> <poop
from="Myself"><smell>stinky</smell></poop></Example>
*/
function printy($xmlstr){// a combination from the comments below...
$xml = new SimpleXMLElement($xmlstr);
$poop = $xml->addChild("poop");
$poop->addAttribute("from", "Myself");
$poop->addChild("smell", "stinky");
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$domnode = dom_import_simplexml($xml);
$domnode = $doc->importNode($domnode, true);
$domnode = $doc->appendChild($domnode);
return $doc->saveXML();
}
?>