Is it possible to use the DOMDocument class and not allow it to add doc type declarations, head, and body tags? I am writing my current bit of code for a server side include, and it is being rendered on an already well formed page. I don't need additional tags.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Since PHP 5.3.6, you can use a node in echo $DOMDocument->saveHTML($the_node_you_want_to_show)
, before that, I've abused ->saveXML()
with minor fixes. You must however have 1 surrounding included node (e.g. output is <div>...somecontent and nodex....</div>
, or loop through the nodes children if you don't want have 1 surrounding tag;
$html = '';
foreach($rootnode->childNodes as $node){
$html .= $rootnode->ownerdocument->saveHTML($node);
}
回答2:
What @Wrikken said or, for PHP < 5.3.6, just use a regular expression:
$html = preg_replace('~<(?:!DOCTYPE|/?(?:html|body))[^>]*>\s*~i', '', $dom->saveHTML());