How to avoid DOM parsing adding html doctype, <head> and <body> tags?
dom, parsing, php
Solution
I'm actually looking for the same solution. I've been using the following method to do this, however the `<p>` around the text node will still be added when you do `loadHTML()`. I don't there's a way to get around that without using another parser, or there's some hidden flag to tell it to not do that.
This code:
<?php
function innerHTML($node){
$doc = new DOMDocument();
foreach ($node->childNodes as $child)
$doc->appendChild($doc->importNode($child, true));
return $doc->saveHTML();
}
$string = '
Some photos<br>
<span class="naslov_slike">photo_by_ile_IMG_1676-01</span><br />
<span class="naslov_slike">photo_by_ile_IMG_1699-01</span><br />
<span class="naslov_slike">photo_by_ile_IMG_1697-01</span><br />
<span class="naslov_slike">photo_by_ile_IMG_1695-01</span><br />
';
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->loadHTML($string);
$elements = $dom->getElementsByTagName('span');
$spans = array();
foreach($elements as $span) {
$spans[] = $span;
}
foreach($spans as $span) {
$span->parentNode->removeChild($span);
}
echo innerHTML( $dom->documentElement->firstChild );
Will output:
<p>Some photos<br><br><br><br><br></p>
However of course this solution does not keep the markup 100% intact, but it's close.
Problem
``` <? $string = ' Some photos<br> <span class="naslov_slike">photo_by_ile_IMG_1676-01</span><br /> <span class="naslov_slike">photo_by_ile_IMG_1699-01</span><br /> <span class="naslov_slike">photo_by_ile_IMG_1697-01</span><br /> <span class="naslov_slike">photo_by_ile_IMG_1695-01</span><br /> '; $dom = new DOMDocument(); $dom->loadHTML($string); $dom->preserveWhiteSpace = false; $elements = $dom->getElementsByTagName('span'); $spans = array(); foreach($elements as $span) { $spans[] = $span; } foreach($spans as $span) { $span->parentNode->removeChild($span); } echo $dom->saveHTML(); ?> ``` I'm using this code to parse strings. When string is returned by this function, it has some added tags: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html><body><p>Some photos<br><br><br><br><br></p></body></html> ``` Is there any way to avoid this and to have clean string returned? This input string is just for example, in usage it can be any html string.