Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php DOMDocument adds <html> headers with DOCTYPE declaration

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?

like image 337
matt Avatar asked Feb 03 '23 20:02

matt


2 Answers

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.
like image 70
Pascal MARTIN Avatar answered Feb 05 '23 16:02

Pascal MARTIN


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.

like image 32
Tiago A. Avatar answered Feb 05 '23 14:02

Tiago A.