php DOMDocument adds <html> headers with DOCTYPE declaration

假如想象 提交于 2019-12-23 07:38:38

问题


I'm adding a #b hash to each link via the DOMDocument class.

        $dom = new DOMDocument();
        $dom->loadHTML($output);

        $a_tags = $dom->getElementsByTagName('a');

        foreach($a_tags as $a)
        {
            $value = $a->getAttribute('href');
            $a->setAttribute('href', $value . '#b');
        }

        return $dom->saveHTML();

That works fine, however the returned output includes a DOCTYPE declaration and a <head> and <body> tag. Any idea why that happens or how I can prevent that?


回答1:


That's what DOMDocument::saveHTML() generally does, yes : generate a full HTML Document, with the Doctype declaration, the <head> tag, ...

Two possible solutions :

  • If you are working with PHP >= 5.3, saveHTML() accepts one additional parameter that might help you
    • see The DOM Goodie in PHP 5.3.6 for more informations.
  • If you need your code to work with PHP < 5.3.6, you'll have to use some str_replace() or regex or whatever equivalent you can think of to remove the portions of HTML code you don't need.
    • For an example, see this note in the manual's users notes.



回答2:


The real problem is the way the DOM is loaded. Use this instead: $html->loadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

Please upvote the original answer here.




回答3:


Adding $doc->saveHTML(false); will not work and it will return a error because it expects a node and not bool.

The solution I used:

return preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $doc->saveHTML()));

I`m using PHP >5.4




回答4:


I solved this problem by creating new DOMDocument and copying child nodes from original to new one.

function removeDocType($oldDom) {
  $node = $oldDom->documentElement->firstChild
  $dom = new DOMDocument();
  foreach ($node->childNodes as $child) {
    $dom->appendChild($doc->importNode($child, true));
  }
  return $dom->saveHTML();
}

So insted of using

return $dom->saveHTML();

I use:

return removeDocType($dom);


来源:https://stackoverflow.com/questions/5444510/php-domdocument-adds-html-headers-with-doctype-declaration

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!