Page 1 of 1
Getting DOMDocument to ommit the XML declaration
Posted: Mon Jun 11, 2007 4:40 am
by Ollie Saunders
Does anyone how (and if it is even possible) to get DOMDocument to omit the XML declaration at the top:
Problem code:
Code: Select all
$dom = new DOMDocument();
$dom->loadXml('<root>foo</root>');
return $dom->saveXml(); // returns <?xml version="1.0"?><root>foo</root>
My current solution is to use substr(). I would try and use DOMDocumentFragment but it doesn't have any functionality for converting it back to a string.
Posted: Mon Jun 11, 2007 8:08 am
by volka
There's support for that in recent libxml2 versions but (afaik) not in the php module yet.
Posted: Mon Jun 11, 2007 8:14 am
by NumberNineteen
Just curious... why would you want to do that?
Posted: Mon Jun 11, 2007 2:39 pm
by Ollie Saunders
If I want to process HTML and echo it in the middle of an HTML document. If you use the loadHTML() type methods it's even worse because it adds a doctype as well.
Posted: Mon Jun 11, 2007 3:00 pm
by NumberNineteen
Ahh... gotcha.
As an option, you could load your XML as you currently are and do a simple XSL transform on it (using an xsl:copy to output the exact format as the source XML) and set your xsl:output to use the omit-xml-declaration attribute: <xsl:output method = "xml" omit-xml-declaration = "yes" />
It's a few more lines of code, but will do what you need to do.
Posted: Mon Jun 11, 2007 3:04 pm
by Ollie Saunders
Yes I know about that but my server doesn't have XSL support and it is considerably more lines that substr().
Posted: Mon Jun 11, 2007 3:17 pm
by NumberNineteen
I think a regular expression to match and delete that string might be the way to go. I say this without having tried it...
Posted: Mon Jun 11, 2007 3:58 pm
by NumberNineteen
I was intrigued to see if it would work, so here you go:
Code: Select all
<?php
$dom = new DOMDocument();
$dom->loadXml('<root><stuff>foo</stuff></root>');
$theXMLSource = $dom->saveXml();
$pattern = '^<\?xml version\=\"1\.0\"\?>\n<^';
$output = preg_replace($pattern, "<", $theXMLSource);
echo $output;
?>
Posted: Mon Jun 11, 2007 5:52 pm
by Ollie Saunders
Dude, substr() is much easier.
Code: Select all
echo substr($output, strlen('<?xml version="1.0"?> '));
Posted: Mon Jun 11, 2007 10:00 pm
by NumberNineteen
HA! I completely misread your original post... I thought substr wouldn't work.
